I don't quite understand the Shift Bitwise operators >> and <<

Hi everyone,

I don't understand how these two shift operators work. I'd be thankful for any help.

``````shift_right = 0b1100
shift_left = 0b1

shift_right = shift_right >> 2
shift_left = shift_left << 2

print bin(shift_right) #0b11
print bin(shift_left)   #0b100
``````

Remember that little trick we all taught in primary school when it comes to multiplying by 10, 100, 1000 etc. We shifted the numbers to the left by 1,2,3 decimal places. Dividing by 10, 100, 1000 etc was a rightward shift by 1,2 or 3.

So a bitwise shift to the left is like multiplying your binary number by 2,4,8,16 etc depending on how many bits you shifted it to the left. A bitwise shift to the right is a like a floor division by 2,4,8,16 etc depending on the number of bits you shifted you number to the right.

shift_left was 1(in binary and decimal) you shifted it two places to the left, multiply by 4, 4 in binary is 100

shift_right was 1100(12 in decimal units) you shifted it two places to the right, division by 4 which gives you 3 in decimal units) 3 in binary form is 11 HatBat over 5 years ago

Good comment ; ) Trishna Guha almost 5 years ago

Thanks a lot for making me understand :) Schweicen over 4 years ago

Great answer, but why mathematically it's FLOOR division in this case? Victor Arjona over 4 years ago

Schweicen, I'm sure someone else will be able to answer this better than I can but I believe it has to do with the fact that it only deals with integers. For example, 14.8 as an integer in Python is read as 14 only. It does not round up, it only takes into consideration the integer in the number. Hope this helps and IF I'm wrong someone please correct me as I'd like to know if I'm right or learn a little from this as well. Good day!

Note the position of the binary digits before and after the shifts.

`0b1100` shifted by two bits to the right moves the `0`s off the end and the two `1`s to the right-most positions.

`0b1` shifted by two bits to the left moves the `1` to the left by two places, and must fill in the two right-most bits with `0`s. kp_569 over 5 years ago

What I do not understand is what is the whole purpose of this?... Any practical reason that we need to go through all these binary exercises? songofsongs over 5 years ago

Same page. I understand how the operators work but not how can this possibly be used practically? Why would we multiply with 2,4,16, etc using these? Is is that much faster than math operations? KuroSetsuna29 over 5 years ago

As mentioned, bitwise operators are not used in most practical programming applications, however it is nice to at least recognize them when you see them as they are not very hard to understand what they do. There is also a very small niche of programming that uses bitwise operators extensively, most of which deal with hardware and low-level programming. sowen1 over 4 years ago