Python: Why is the right shift >> rounded down and where should it be used?

I never used operators, >>and <<not because I never needed them, but because I did not know if I could use them or wherever I was.

100 >> 3prints 12instead 12.5. Why is this. Perhaps studying where it is best to use the right shift will answer implicitly, but I'm curious.

+3
source share
4 answers

Right shift is not a division

Let's see what the right-shift actually does , and that will become clear.

, . 8 , 2 00000010 5 00000101.

. , 00000001 00000010.

, ( right -most) .

+13

>> << - . .

>>> bin(100)
'0b1100100'
>>> bin(12)
'0b1100'
+4

, , 100 → 3

100
128 64 32 16 8 4 2 1
  0  1  1  0 0 1 0 0 = 100
100 >> 1
128 64 32 16 8 4 2 1
  0  0  1  1 0 0 1 0  = 50
100 >> 2
128 64 32 16 8 4 2 1
  0  0 0  1  1 0 0 1  = 25
100 >> 3
128 64 32 16 8 4 2 1
  0  0  0  0 1 1 0 0  = 12

, 2, . , , .

, - , , , . , , ID3, 7- , :

0xxxxxxx 0xxxxxxx 0xxxxxxx 0xxxxxxx.

:

0000xxxx xxxxxxxx xxxxxxxx xxxxxxxx

.

+2

- . , 12 0b1100. 1 , 0b110 = 6. 2, 0b11 = 3. , , 3, 0b1 = 1, 1.5. , , , .

One easy way to think about this is to shift to the right by N, which is the same as dividing by 2 ^ N and then truncating the result.

+1
source

Source: https://habr.com/ru/post/1733963/


All Articles