Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Bit Shifting ?

by mitd (Curate)
on Apr 06, 2003 at 02:33 UTC ( #248376=perlquestion: print w/replies, xml ) Need Help??
mitd has asked for the wisdom of the Perl Monks concerning the following question:

I know the uber Perlies will unravel this one without
breaking a sweat. Perhaps a the newer Perlites will take
a crack.

Why does this:

my ($perms, $type) = @ARGV; print "Other Test: ", ($perms & $type ) ,"\n"; print "Group Test: ", ($perms & ($type << 3 )),"\n"; print "Owner Test: ", ($perms & ($type << 4)),"\n"; # with command line params: 63,1;

Produce this:

Other Test: 0
Group Test: 8
Owner Test: 16

And this:

my ($perms, $type) = @ARGV; print "Other Test: ", ($perms & ($type << 0) ,"\n"; print "Group Test: ", ($perms & ($type << 3 )),"\n"; print "Owner Test: ", ($perms & ($type << 4)),"\n"; # with command line params: 63,1;

Produce this:

Other Test: 1
Group Test: 8
Owner Test: 16

Well snap my deerskin thong! I just figured her out,
but shoot I think I'll post her anyways.

mitd-Made in the Dark
I've always been astonished by the absurd turns
rivers have to make to flow under every bridge.

Replies are listed 'Best First'.
Re: Bit Shifting ?
by MarkM (Curate) on Apr 06, 2003 at 03:21 UTC

    @ARGV is an array of strings. Bitwise OR or AND of strings in Perl results in a byte-by-byte OR or AND. Compare:

    $ perl -e "print 1 & 63, qq(\n)" 1 $ perl -e "print q(1) & q(63), qq(\n)" 0

    As an integer bitwise AND, the result is 1. As a string bitwise AND, the result is 0. Why? As a string, ord("1") & ord("6") yields ord("0"). To try something cool, try:

    $ perl -e "print q(a) & q(ab), qq(\n)" a

    Similarily, ord("a") & ord("a") yields ord("a"). (The characters on the end don't count for bitwise AND since the strings have a different length, and Perl doesn't explicitly include the "\0" characters at the end)

    Any time you have a scalar that may be in string context that you need to manipulate as a number, consider using a common expression such as '0+$scalar' to force it to have a numeric representation. @ARGV appears to be just such a case.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://248376]
Approved by diotalevi
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2016-10-27 01:27 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (351 votes). Check out past polls.