How does bit shifting work?


#1

Question

How does bit shifting work?

Answer

An easy way to look at bit shifting is to visually move the bits in the specified direction by the specified amount. If we have a bit string of 1000 and shift right by 1, we end up with 0100. Shift right by another 1 and we get 0010.
If we have 0010 and shift right by 2, however, we lose our bit! And there’s no getting it back after it falls of the beginning or end, so be careful! We’d end up with 0000.
So given some variable like my_bit_string = 0b1000, we can get 0b0001 by doing my_bit_string = my_bit_string >> 3.


FAQ: Learn Python - Introduction to Bitwise Operators - Slide to the Left! Slide to the Right!