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

After having searched for a while and trying to figure it out, I am at the mercy of Perl Monks. Here is the code that should effectively right rotate $p, bitwise, by 1 spot each time through the loop:

for($a = 0; $a < ($n % $SIZE); $a++) { $carry = 0x1 & $p; #extract least significant bit $p >>= 1; #shift $p by one spot to the right if($carry == 1) #to rotate in a leading 1 { my $or = 2 ** ($SIZE - 1); #$SIZE is # of bits in $p print "OR: $or\n"; print "pre|: $p. carry: $carry\n"; $p |= $or; #bitwise or in $or to add the leading 1 to $p } print "$a-$p\n"; }
I am using Perl 5.6.1. Here are some sample outputs for a given $p.

#this case works when $SIZE = 32 and $n = 3
p: 204229738. #ok
0-102114869 #ok, carry was 0 before 1st shift
OR: 2147483648 #carry is 1 before 2nd shift
pre|: 51057434. carry: 1 #p after second shift
1-2198541082 #p after | with $or
2-1099270541 #p after third shift

#this case fails when $SIZE = 40 and $n = 1
p: 418262508595. #ok
OR: 549755813888 #ok
pre|: 2147483647. carry: 1 #not ok
0-4294967295 #not ok

It seems that anything of size 5 bytes or greater fails consistently. Any thoughts why and how to combat this?

Replies are listed 'Best First'.
Re: Bitwise ops inconsistent
by Zaxo (Archbishop) on Aug 24, 2005 at 00:21 UTC

    use Math::BigInt; You can stretch to eight bytes if your perl is compiled to handle 64-bit integers.

    After Compline,
    Zaxo

      use Math::BigInt;
      But not the one shipped with 5.6.1; upgrade to the latest version on CPAN.
Re: Bitwise ops inconsistent
by pg (Canon) on Aug 24, 2005 at 01:26 UTC

    Your numbers have been sliently converted to floating (when they are too big for integer), and those integer operators no longer produce meaningful results (or as those good documents put: result is undefined)

Re: Bitwise ops inconsistent
by GrandFather (Saint) on Aug 24, 2005 at 00:22 UTC

    First, you should provide a complete example including the data that generates the result shown.

    Second, your results would be much clearer of you printed hex rather than decimal numbers (use printf "OR: %08x\n", $or; for example).

    Third, always use strict; use warnings;


    Perl is Huffman encoded by design.
Re: Bitwise ops inconsistent
by QM (Parson) on Aug 24, 2005 at 15:31 UTC
    Excellent advice above. I'd add/enhance it by saying:
    use integer;
    might help, or use bit vectors;

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of