in reply to Bitwise & with large numbers

meditate on the output of this: :)
use strict; for (0..20,) { $a = dec2bin($_+1); $b = dec2bin($_); print "$a = ", $_ + 1, "\n", "$b = ", $_, "\n", "--------\n", dec2bin(($_+1) & $_), " = ", (($_+1) & $_), "\n\n"; } # Perl Cookbook recipe 2.4. sub dec2bin { my $s = unpack("B32", pack("N",shift)); #$s =~ s/^0+(?=\d)//; $s = substr($s,-8,8); return $s; }
UPDATE: thanks tachyon!

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)
-->

Replies are listed 'Best First'.
Re: (jeffa) Re: Bitwise & with large numbers
by tachyon (Chancellor) on Apr 03, 2002 at 04:29 UTC

    Actually Anonymonk has a valid point as this is a buffer overflow type bug. 4294967296 is a 33 bit integer, which is of course one bit more than 32. Perhaps you should meditate on this:

    print "2**32 is: ", 2**32, "\n"; print <<TEXT; This is what we should have: 100000000000000000000000000000000 = 4294967296 011111111111111111111111111111111 = 4294967295 ---------------------------------------------- 000000000000000000000000000000000 = 0 But we get a buffer overflow like so, resulting in erroneous output: TEXT for (4294967295) { $a = dec2bin($_+1); $b = dec2bin($_); print "$a = ", $_ + 1, "\n", "$b = ", $_, "\n", "--------\n", dec2bin(($_+1) & $_), " = ", (($_+1) & $_), "\n\n"; } sub dec2bin { return unpack("B*", pack("N",shift)); }

    I have no call for it personally but Math::BigInt might be useful.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print