Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: bitwise shift operator

by GrandFather (Saint)
on Apr 19, 2007 at 01:02 UTC ( #610880=note: print w/replies, xml ) Need Help??


in reply to bitwise shift operator

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

Replies are listed 'Best First'.
Re^2: bitwise shift operator
by jwkrahn (Monsignor) on Apr 19, 2007 at 01:50 UTC
    Or consider this which doesn't use multiplication (but only works on a 32 bit machine.)
    $ perl -le'print ~0 + 1' 4294967296
Re^2: bitwise shift operator
by Moron (Curate) on Apr 19, 2007 at 18:12 UTC
    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: note [id://610880]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2023-06-07 12:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you go to conferences?






    Results (29 votes). Check out past polls.

    Notices?