Perl-Sensitive Sunglasses PerlMonks

### Comment on

 Need Help??

Here's a solution that works on hex strings, so allows you to work with hex numbers larger than the maximum integers Perl can handle...

```use 5.010;
use strict;
use Carp qw/croak/;
use List::Util qw/max/;

sub xor_strings
{
croak "should be passed two arguments" unless @_==2;
state \$chunk_size = 4;
state \$pattern    = sprintf '%%0%dx', \$chunk_size;

# Make strings equal length, and a multiple of \$chunk_size.
my \$length = max(map { length \$_ } @_);
\$length += \$chunk_size - (\$length % \$chunk_size);
my @strings = map { ('0'x(\$length - length \$_)) . \$_ } @_;

# Join results of each chunk
return join q{},
map {
# Parse chunk hex to an integer
my \$i = \$_;
my @nums = map { hex substr \$_, \$i*\$chunk_size, \$chunk_siz
+e } @strings;
# Xor them and convert to hex.
sprintf \$pattern, \$nums[0] ^ \$nums[1]
}
0 .. (\$length/\$chunk_size)-1;
}

say xor_strings(
'112233112233112233112233112233112233112233112233112233',
'aabbccaabbccaabbccaabbccaabbccaabbccaabbccaabbcc112233',
);

The chunk size of 4 is fairly conservative. It means that the string in processed in four-digit (i.e. 16 bit) chunks. You can probably get a minor speed up using a larger chunk size if you know that your computer will be able to handle it. The returned value will be left-padded with zeroes to be a length that is a multiple of the chunk size.

perl -E'sub Monkey::do{say\$_,for@_,do{(\$monkey=[caller(0)]->[3])=~s{::}{ }and\$monkey}}"Monkey say"->Monkey::do'

In reply to Re^3: Hex String XOR by tobyink
in thread Hex String XOR by alanonymous

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (12)
As of 2017-07-26 07:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I came, I saw, I ...

Results (385 votes). Check out past polls.