Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

bitwise shift operator

by perlknight (Pilgrim)
on Apr 19, 2007 at 00:53 UTC ( #610879=perlquestion: print w/replies, xml ) Need Help??

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

    Prints:

    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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://610879]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2023-06-08 10:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you go to conferences?






    Results (29 votes). Check out past polls.

    Notices?