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

# Please explain Shift Operator

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

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
2
>>>``````

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)
'0b100'
>>> bin(2)
'0b10'
>>> bin(89)
'0b1011001'
>>> ``````

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)
'0b10101'
>>> ``````

Let’s try a left shift in IDLE…

``````>>> bin(int(0b1001) << 2)
'0b100100'
>>> ``````

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

What is `0b100100`?

``````>>> int(0b100100)
36``````

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

Thanks