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

fellow monks, I need clarification on this line of code:
$cycle = ((1<<31) * 2);
Does this mean, shift binary 1 to the left 31 bit and * 2?

Replies are listed 'Best First'.
Re: bitwise shift operator
by GrandFather (Saint) on Apr 19, 2007 at 01:02 UTC

    The parenthesis control the execution order so the 1 gets shifted left 31 places, then the result is multiplied by 2. Note that this is a trick to get around Perl's internal representation for integers (on many platforms) as 32 bit quantities. Consider:

    print 1<<31, "\n"; print 2 * (1<<31), "\n"; print 1<<32, "\n"; print 2**32, "\n";


    2147483648 4294967296 1 4294967296

    Although it's not clear to me why 2**32 was not used - your code seems rather odd to me.

    DWIM is Perl's answer to Gödel
      Or consider this which doesn't use multiplication (but only works on a 32 bit machine.)
      $ perl -le'print ~0 + 1' 4294967296
      I can imagine that 2**32 might not be optimised into anything cheaper. 2.1**3.1 would always be expensive for example and you don't expect an interpreter to be looking for a bit-shift optimisation because that would slow ** down even more if one didn;t exist. By comparison, << is a very cheap operator when translated down to machine code level and ** is one of the dearest.

      ^M Free your mind!