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

Hello:
In postgresql, I was taught how to take a big integer, get the last 5 bits, and make a decimal number out of that. For example:
> SELECT -9133545115225966845 &31; ?column? ---------- 3
How do I do the same thing in perl?
Thanks

Replies are listed 'Best First'.
Re: The last 5 bits in perl
by FunkyMonk (Bishop) on Aug 06, 2009 at 21:02 UTC
    Unsurprisingly...

    my $last_5_bits = -9133545115225966845 & 31; # 3

    although I'd prefer hex (but that's just me)

    my $last_5_bits = -9133545115225966845 & 0x1f; # still 3

Re: The last 5 bits in perl
by kennethk (Abbot) on Aug 06, 2009 at 21:08 UTC
    In addition to FunkyMonk's suggestion for Bitwise And, you can also use the modulus % (Multiplicative Operators) with 32, which may be more obvious to a maintainer.

    my $last_5_bits = -9133545115225966845 % 32; # 3

    For your example, you'll likely need to use bigint.

      ... and it's even more obvious that it's 5 bits if you write the 32 as 2**5.

      Note that Perls integers use only 32 (or sometimes 64) bits, and they are signed, so every number larger than 2^31 (or 2^63) is silently converted to a floating point number, loosing some precision when the number grows big:

      perl -e "print 1234567890123456789012345678900 % 2" 0 perl -e "print 1234567890123456789012345678901 % 2" 0

      Math::BigInt can help:

      perl -MMath::BigInt -e "print Math::BigInt->new('123456789012345678901 +2345678900') % 2" 0 perl -MMath::BigInt -e "print Math::BigInt->new('123456789012345678901 +2345678901') % 2" 1

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)