Delete Icon
This forum is now read-only. Please use our new forums at
0 points
Submitted by আরফীণ
5 years ago

Please explain Shift Operator

What does << and >> operators do? i don’t understand :(

Answer 558e9302e0a3003aec0009fe

3 votes


In a digital computer, all data is stored as a series of bits. Each bit has either of two values, which can be represented conceptually as 0 or 1.

In a binary, or base 2, numbering system, we can represent integers based on their internal sequence of bit values, as follows …

1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001

… etc.

The shift operators, << (shift left), and >> (shift right), take two integers as operands. They return the result of shifting the bits of the left operand by the number of positions specified by the right operand. The left shift operator shifts bits to the left, and the right shift operator shifts bits to the right.

Consulting the list of integers and their bit representations above, we can predict that …

4 >> 1

… will shift the 1 in 4‘s bit representation by 1 position to the right, resulting in 010, or, more succinctly, 10. Looking at the chart again, we see that 10 is the bit representation for 2. So, the result is 2. Lets try it in IDLE …

>>> print 4 >> 1

Yep, sure enough …

We can see an integer’s bit representation by using the bin function to convert it to a string. In IDLE …

>>> bin(4)
>>> bin(2)
>>> bin(89)

We can convert an integer to a string representing its bit sequence with the bin function. The binary strings are prefixed with 0b. Some more iDLE action …

>>> bin(21)

Let’s try a left shift in IDLE…

>>> bin(int(0b1001) << 2)

The 1s have each shifted by 2 positions to the left.

What is 0b100100?

>>> int(0b100100)

A good way to get familiar with this material is to experiment with it.

17840 points
Submitted by Glenn Richard
5 years ago


Nicholas 5 years ago


Answer 55c071bdd3292f8df000047a

0 votes


Great answer @Glen I would also suggest working out some of these operations by hand on paper so that you gain a deep understanding of what is happening and check yourself using IDLE

993 points
Submitted by Phyllis
5 years ago