Jpaji Rajnish
Jpaji Rajnish

Reputation: 1501

Variable assignment with ">>" and "&" operators

I've been trying to understand a Python script and I can't figure out what this assignment is doing:

data_byte2 = value >> 7 & 127

I've seen a kind of similar construct with the or operator but never with & and I have no idea at all what >> does (nothing's coming up on Google for it).

Upvotes: 2

Views: 897

Answers (3)

Hackaholic
Hackaholic

Reputation: 19733

>> is right shift operator

>>> 3 >> 1
1

binary of 3 is 00011, now shift one bit towards right the so it will be 00001 so we get answer 1

>>> 3 >> 2
0

binary of 3 is 00011, now shift two bit towards the right, so it will be 0000, so output is 0

Upvotes: 0

Maroun
Maroun

Reputation: 95948

value >> 7 & 127

Is like writing:

(value >> 7) & 127  # see Python Operators Precedence

First you rightshift value by 7, then & result with 127.

127 in binary is 1111111, when you & with this number, you're clearing all bits on left of the number. For example, if you have 16 bit number:

1101011101111101
→

Shifting it 7 to the right will result in:

0000000110101110

& with 127 will keep only most right 8 bits:

0000000110101110
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
0000000001111111  & (127)
----------------
0000000000101110

Upvotes: 4

jonrsharpe
jonrsharpe

Reputation: 121976

>> is the right bit-shift operator, and & is bitwise AND.

This is easier to see if you look at numbers in binary form.


>>> format(13, "08b")
'00001101'
>>> format(13 >> 1, "08b")
'00000110'

You can see that the binary digits are right-shifted by one place (this is equivalent to a division by 2, so x >> y is equivalent to x // (2 ** y)). On that basis, x >> 7 means "shift x's bits seven places to the right", or "divide x by 128".


>>> format(10, "08b")
'00001010'
>>> format(7, "08b")
'00000111'
>>> format(10 & 7, "08b")
'00000010'

Here the output includes a 1 for every bit where both inputs have 1, 0 otherwise. Given that

>>> format(127, "08b")
'01111111'

x & 127 means "take the last seven bits of x".


As >> has higher operator precedence than &, the expression

value >> 7 & 127

means "divide value by 128 then take the last seven bits".

Upvotes: 2

Related Questions