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?


In reply to Understanding Shift Operators by spickles

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.