Slide Left, and then Slide Right over the mountain!


The next two operations we are going to talk about are the left and right shift bitwise operators. These operators work by shifting the bits of a number over by a designated number of slots.

The block below shows how these operators work on the bit level. Note that in the diagram, the shift is always a positive integer:

# Left Bit Shift (<<)  
0b000001 << 2 == 0b000100 (1 << 2 = 4)
0b000101 << 3 == 0b101000 (5 << 3 = 40)       

# Right Bit Shift (>>)
0b0010100 >> 3 == 0b000010 (20 >> 3 = 2)
0b0000010 >> 2 == 0b000000 (2 >> 2 = 0)

This operation is mathematically equivalent to floor dividing and multiplying by 2 (respectively) for every time you shift, but it's often easier just to think of it as shifting all the 1s and 0s left or right by the specified number of slots.

Note that you can only do bitwise operations on an integer. Trying to do them on strings or floats will result in nonsensical output!

Shift the variable shift_right to the right twice (>> 2) and shift the variable shift_left to the left twice (<< 2). Try to guess what the printed output will be!

-Help. I have no idea this means.


Oh. Also thx to @mtf


In english, the prefix, bi- refers to two. For instance, we upright walking animals are bipeds which loosely translates to two footed. Binanry numbers have a base of two, so the digits are either zeros or ones.


is a binary integer. The computer recognizes it as binary by the 0b prefix attached to the digits. The above number is the decimal equivalent of 8.

When multiplying by 2, the computer simply shifts the bits to the left by one.

  8    *   2  ==   16

0b1000 * 0b10 == 0b10000

Notice that the bits shifted to the left by one.

  10   *   2  ==   20

0b1010 * 0b10 == 0b10100

In other words, 8 << 1 == 16, and, 10 << 1 == 20.

Division by 2 is a little tricky since binary numbers do not have decimal fractions. That is why the lesson refers to it as floor division.

7 / 2 == 3.5  and  7 // 2 == 3

7 >> 1 == 3

Let's look at the binary representation...

0b111 >> 1 == 0b11

Division by 2 is a shift to the right of the bits, but instead of adding a zero to the right side, we drop a bit from the right side, hence the floor value.




Also... I still am reading over the lambda stuff you sent me.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.