views:

93

answers:

1

I've been having this problem in Perl for a few days now, and after scouring countless man pages, perldocs and googling too many search terms, hopefully someone here can help me out.

I am given two strings which represent hex values, i.e. "FFFF", not the Perl hex number 0xFFFF. Given two of these strings, I wish to convert them to binary form, perform a bitwise AND of the two, then take the output of this and examine each bit from LSB to MSB.

I have two problems right now; converting the hex string into a hex number, and shifting the result of the bitwise AND.

For converting the hex string into a hex number, I've tried the following approaches which don't seem to work when I print them out to examine:

$a = unpack("H*", pack("N*", $a));

$a = sprintf("%H", $a);

Using a 'print' to examine each of these does not show a correct value, nor does using 'sprintf' either...

The second problem I have occurs after I perform a bitwise AND, and I want to examine each bit by shifting right by 1. To avoid the previous problem, I used actual Perl hex numbers instead of hex strings (0xffff instead of "ffff"). If I try to perform a shift right as follows:

#Convert from hex number to binary number

$a = sprintf("%B", $a);
$b = sprintf("%B", $b);

$temp = pack("B*", $a) & pack("B*", $b);
$output = unpack("B*", $temp);

At this point everything looks fine, and using a 'print' I can see that the values of the AND operation look right, but when I try to shift as follows:

$output = pack("B*", $output);
$output = $output >> 1;
$output = unpack("B*", $output);

The resulting value I get is in binary form but not correct.

What is the correct way of performing this kind of operation?

+9  A: 

There's no such thing as a "hex number". A number is a number, a hexadecimal representation of a number is just that - a representation.

Just turn it into a number and use bitwise and.

my $num = (hex $a) & (hex $b);
print ($num & 1, "\n") while ($num >>= 1)
Anon.
Did you mean `while ($num >>= 1)` ?
mobrule
@mobrule: Probably, yeah. Thanks.
Anon.
Ah thanks, it's much more clear now
materiamage