spickles has asked for the wisdom of the Perl Monks concerning the following question:
I am trying to understand someone else's code, and I was very curious as to what the binary shift operator does. So I looked it up on perldoc.perl.org and found this definition:
Binary "<<" returns the value of its left argument shifted left by the number of bits specified by the right argument. Arguments should be integers. (See also "Integer Arithmetic".)
Seems rather straight forward, so I created the following code to test:
#!c:/perl/bin/perl use strict; use warnings; print 1 << 1; print "\n"; print 1 << 2; print "\n"; print 1 << 3; print "\n"; print 1 << 4; print "\n"; print 1 << 5; print "\n"; print 1 << 6; print "\n"; print 1 << 7; print "\n"; print 1 << 8; print "\n"; print 1 << 9; print "\n"; print 1 << 10; print "\n"; print 2 << 1; print "\n"; print 2 << 2; print "\n"; print 2 << 3;
Everything made sense to me until I started using the last few beginning with print 2 << 1. I was surprised that it compiled without error and produced what I am assuming to be valid output. If the shift operator is used with binary and it shifts the argument on the left by the number of bits specified by the argument on the right, then aren't the only valid arguments for the left side 0 and 1? How does it produce output with numbers 2 and up? Does it convert the decimal number 2 to binary and then shift each bit?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Understanding Shift Operators
by FunkyMonk (Bishop) on Apr 06, 2010 at 20:52 UTC | |
|
Re: Understanding Shift Operators
by roboticus (Chancellor) on Apr 06, 2010 at 20:51 UTC | |
|
Re: Understanding Shift Operators
by toolic (Bishop) on Apr 06, 2010 at 20:53 UTC | |
by 7stud (Deacon) on Apr 06, 2010 at 21:03 UTC | |
by ikegami (Patriarch) on Apr 06, 2010 at 21:23 UTC | |
by toolic (Bishop) on Apr 06, 2010 at 23:19 UTC | |
by spickles (Scribe) on Apr 07, 2010 at 00:27 UTC | |
by 7stud (Deacon) on Apr 06, 2010 at 21:49 UTC | |
by Anonymous Monk on Apr 06, 2010 at 22:14 UTC | |
by ssandv (Hermit) on Apr 06, 2010 at 23:05 UTC |