-8

I tried to find answer here, but didn't find.

What does ">>" and "<<" means in python?

Examples in interpreter:

In [9]: 23 >> 64
Out[9]: 0

In [10]: 23 << 64
Out[10]: 424275113695319687168L

In [11]: 1 >> 2
Out[11]: 0

In [12]: 32132345235423451 >> 2
Out[12]: 8033086308855862

In [13]: 321323452354566423451 >> 2
Out[13]: 80330863088641605862L

In [14]: 2 >> 2
Out[14]: 0

In [15]: 233 >> 2
Out[15]: 58

In [16]: 33 >> 2
Out[16]: 8

In [17]: 3 >> 2
Out[17]: 0

Find usage here https://stackoverflow.com/a/14854406/4436022

Community
  • 1
  • 1
Yuriy Leonov
  • 536
  • 1
  • 9
  • 33

3 Answers3

1

<< and >> are the Binary Left Shift and Binary Right Shift respectively.

The left operands value is moved left by the number of bits specified by the right operand.

Example, Code: temp = 14 << 2 The variable temp has a value of 56 because 14 (00001110 in binary) shifted left two bits equals 56 (00111000 in binary).

The left operands value is moved right by the number of bits specified by the right operand.

Example, Code: temp = -14 >> 2 temp has a value of -4: -14 (11110010 in two's complement binary) shifted right two bits equals -4 (11111100 in two's complement binary).

Vaulstein
  • 20,055
  • 8
  • 52
  • 73
1

It's bit shift, like in C. Please read this link.

Basically << 1 multiplies an integer by 2 in a fast way while >> 1 do a integer division by 2. << n is like doing << 1 n times, so it multiplies by 2**n. In the same way, >> n do an integer division by 2**n.

Technically, if you represent your numbers in binary (as computers do), << shift all the bits on the left and >> shifts all the bits to the right.

Thus 3, represented in binary by (00000011) becomes (00001100) when applied with <<2. (00001100) is the representation of 12. Again, 3>>1 shift (00000011) to (00000001) which is 1, the same result as 3 div 2.

Lærne
  • 3,010
  • 1
  • 22
  • 33
0

These operators are bit shift :

  • >> shifts the bit pattern to the right - i.e. moves all the bits to the right - equivalent to dividing by a power of two

  • << shifts the bit patter to the left - i.e. moves all the bits to the left - equivalent to multiplying by a power of two :

5 >> 2 = 1 : equivalent to

101 base 2 shifted right by 2 = 001 base 2 = 1

and

1 << 2 = 4 : equivalent to

001 base 2 shifted left by 2 = 100 base 2 = 4

Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33