in reply to The last 5 bits in perl

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.

Replies are listed 'Best First'.
Re^2: The last 5 bits in perl
by moritz (Cardinal) on Aug 06, 2009 at 21:35 UTC
    ... and it's even more obvious that it's 5 bits if you write the 32 as 2**5.
Re^2: The last 5 bits in perl
by afoken (Chancellor) on Aug 08, 2009 at 18:14 UTC

    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". ;-)