Understanding bitwise operators


#1

Would someone help me better understanding how bitwise operators work? Here is the given explanation and examples:

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.

# 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)

Yet, just looking at the first example of 1 << 2:
1 // 2 = 0
0 // 2 = 0
0 * 2 = 0
0 * 2 = 0

or then 5 << 3:
5 // 2 = 2
2 // 2 = 1
1 // 2 = 0
0 * 2 = 0
0 * 2 = 0
0 * 2 = 0

It appears I am not understanding this math properly.

Any clarity is appreciated :slight_smile:


#2

A left shift (<<) is multiplying by 2, a right shift (>>) is dividing by 2. with the lowest quotient being 0.

12 // 2 = 6
6 // 2 = 3
3 // 2 = 1
1 // 2 = 0

So 12 >> 4 = 0. Think of it as floor divide 12 by 2**4, 12 // 16 = 0

1 << 4 is the equivalent of 1 * (2**4), or 16
1 << 1 = 2
2 << 1 = 4
4 << 1 = 8
8 << 1 = 16


#3

Thank you @mtf! This makes sense now :slight_smile: