[Tutor] << operator ? [left bitwise shifting]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 10 Apr 2002 14:07:22 -0700 (PDT)


On Wed, 10 Apr 2002, Prahlad Vaidyanathan wrote:

> What does this "<<" operator do ? IIRC, it is a bit-wise shift operator,
> but I don't know what that means either :-(

On most computer systems, when computers count, they count in two's
because they don't have ten fingers.  So when we start counting like this:

    "0...1...2...3...4...5...6...7...8...9...10...11...12..."

Computers often do something like this:

    "0...1...10...11...100...101...110...111...1000...1001...1010...1011
     ...1100...1101...1110...1111..."

And this is what we mean when we say that computers count in base-two
arithmetic --- they represent numbers by using on/off switches --- "bits".
On most systems that Python runs on, each integer is made up of 32 bits.


It turns out that bits are really useful because we don't have to say that
32 bits always stand for a number: we can use those bits as 32 individual
"yes/no" choices!


Here's a concrete example: the Unix operating system uses numeric codes to
say if a particular file is readable, writable, or executable --- each
file has a "permission" number connected to it.  The number "7", for
example, has the following bit representation:

    111

and could mean "This file is both readable, writable, and executable."
The number "5" is represented as:

    101

and could mean "This file is readable, not writable, and executable."  So
here we can use a number just for the sake of its bit pattern.


The neat thing to see is that we can use numbers for more than just
arithmetic: we can treat numbers as patterns of ones and zeros.  The left
shift operator '<<' allows us to push the bits of a number toward the
left.  Let's try it out:

###
>>> x = 1
>>> x << 1
2
>>> x << 2
4
>>> x << 3
8
>>> x << 4
16
###

X contains the bit pattern:

    1 == "00000000000000000000000000000001"

(32 bits)  So left shifting it once shoves the leftmost zero out into
space, and moves everything else one place to the left.

    2 == "00000000000000000000000000000010"

And it turns out that when we left shift a number, it effectively
"doubles".


Hope this is making some sort of sense... *grin* Please feel free to ask
more questions about this.