Eradicatore has asked for the wisdom of the Perl Monks concerning the following question:

My question is short. I'm trying to use perl to do some bitwise operations. The numbers are large, so I thought it would be nice to use the "string" bitwise AND (that is on page 102 in the 3rd edition of the camel BTW). I have two problems with it though. Here is some example code of the two problems:
#!/usr/local/bin/perl -w use strict; my $key = "24" & "4"; print "Key: $key\n"; my $key2 = "2f" & "4"; print "Key2: $key2\n"; my $key3 = "24" & "04"; print "Key3: $key3\n";
But that outputs:

Key: 0

Key2: 0

Key3: 04

So really only the last case works. It says right in the camel book that it should assume the string is padded with zeros if one string is longer than the other. Also, why on earth can I not use hex digits in this type of operation?

I guess I'm just really frustrated by perls bitwise funcitonality right now. It sure seems difficult to deal with things as bits to me. Anyone know of a good tutorial on this type of thing?

Justin Eltoft

"If at all god's gaze upon us falls, its with a mischievous grin, look at him" -- Dave Matthews

Replies are listed 'Best First'.
Re: bitwise operators
by bikeNomad (Priest) on Jul 18, 2001 at 19:28 UTC
    It is doing bitwise operators, just on the bits in your characters. This is probably not what you want. Look into using pack and unpack:

    my $p1 = pack( 'H*', "24" ); # hex 24 my $p2 = pack( 'H*', "04" ); # hex 4 my $p3 = $p1 & $p2; print unpack( 'H*', $p3 ), "\n"; # prints 04 $p1 = pack( 'H*', "2f" ); $p2 = pack( 'H*', "14" ); $p3 = $p1 | $p2; print unpack( 'H*', $p3 ), "\n"; # prints 3f
Re: bitwise operators
by RatArsed (Monk) on Jul 18, 2001 at 19:10 UTC
    what's your result if you do "42" & "4"? This may answer the zero padding.

    How big are your real numbers? Perl can handle some really large numbers without breaking sweat, so unless you're after really, really, really high precision, I'd stick to doing it numerically...

    --
    RatArsed

      Hmm, "42" & "4" comes out as 4, so I guess its padding on the right side?? That seems odd, but oh well. Any idea on the hex digits, and why I can't use them (a-f)?

      Justin Eltoft

        I haven't tested this, but I expect it just does a bitwise comparison on the characters -- so "F" & "8" != "8"

        --
        RatArsed

Re: bitwise operators
by petral (Curate) on Jul 19, 2001 at 06:18 UTC
    Just another variation on the possible meaning of your words:
    bitwise processsing of numbers as characters (in octal or hex):
    > perl -lwe'$,=$";print unpack"c*", "\24\x2f\52" & "\4\24\x0a"' 4 4 10 >

      p