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).
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
>> 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".
>> 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
Related
This question already has answers here:
>> operator in Python
(5 answers)
Closed 6 years ago.
Someone sent me this equation but I don't understand what it means.
result = ((~c1) >> 1) & 0x0FFFFFF
It has to do with converting the binary from a wiegand reader.
Reference
The >> operator in Python is a bitwise right-shift. If your number is 5, then its binary representation is 101. When right-shifted by 1, this becomes 10, or 2. It's basically dividing by 2 and rounding down if the result isn't exact.
Your example is bitwise-complementing c1, then right-shifting the result by 1 bit, then masking off all but the 24 low-order bits.
This statement means:
result = # Assign a variable
((~c1) # Invert all the bits of c1
>> 1) # Shift all the bits of ~c1 to the right
& 0x0FFFFFF; # Usually a mask, perform an & operator
The ~ operator does a two's complement.
Example:
m = 0b111
x = 0b11001
~x == 0b11010 # Performs Two's Complement
x >> 1#0b1100
m == 0b00111
x == 0b11001 # Here is the "and" operator. Only 1 and 1 will pass through
x & m #0b 1
I am trying to understand bitwise operators in Python 2.7 (<<, >>, &, |, ~ and ^), so my question is: what is the interpreter really seeing and executing? When:
>>> 3 >> 0
3
>>> 3 >> 1
1
and why
>>> 3 >> 2
0
and after that if you increment the second number by one the answer will continue to be 0.
They treat it as if it were a string of bits, written in twos-complement binary. But I do not understand what happens here.
Have a look at the binary representation of these numbers and imagine that there are infinite zeroes to the left:
...0000011 = 3
Now, what >> does is it shifts the binary representation to the right. This is the same as deleting the last digits:
If you shift by 0 places, nothing changes. Therefore, 3 >> 0 is 3.
If you shift by 1 place, you delete the last binary digit:
...0000011 >> 1 = ...000001 = 1
Therefore, 3 >> 1 is 1.
If you shift by 2 or more places, all of the binary ones will be deleted and you are left with only zeroes:
...0000011 >> 2 = ...00000 = 0
This is why 3 >> 2 (or more than 2) is always 0.
I notice that I can do things like 2 << 5 to get 64 and 1000 >> 2 to get 250.
Also I can use >> in print:
print >>obj, "Hello world"
What is happening here?
The >> operator in your example is used for two different purposes. In C++ terms, this operator is overloaded. In the first example, it is used as a bitwise operator (right shift),
2 << 5 # shift left by 5 bits
# 0b10 -> 0b1000000
1000 >> 2 # shift right by 2 bits
# 0b1111101000 -> 0b11111010
While in the second scenario it is used for output redirection. You use it with file objects, like this example:
with open('foo.txt', 'w') as f:
print >>f, 'Hello world' # "Hello world" now saved in foo.txt
This second use of >> only worked on Python 2. On Python 3 it is possible to redirect the output of print() using the file= argument:
with open('foo.txt', 'w') as f:
print('Hello world', file=f) # "Hello world" now saved in foo.txt
These are bitwise shift operators.
Quoting from the docs:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.
12 << 2
48
Actual binary value of 12 is "00 1100" when we execute the above statement Left shift ( 2 places shifted left) returns the value 48 its binary value is "11 0000".
48 >> 2
12
The binary value of 48 is "11 0000", after executing above statement Right shift ( 2 places shifted right) returns the value 12 its binary value is "00 1100".
They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.
| operate | bit value | octal value | description |
| ------- | --------- | ----------- | -------------------------------------------------------- |
| | 00000100 | 4 | |
| 4 << 2 | 00010000 | 16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100 | 4 | move all bits to right 2 bits, filled with 0 at the left |
The other case involving print >>obj, "Hello World" is the "print chevron" syntax for the print statement in Python 2 (removed in Python 3, replaced by the file argument of the print() function). Instead of writing to standard output, the output is passed to the obj.write() method. A typical example would be file objects having a write() method. See the answer to a more recent question: Double greater-than sign in Python.
These are the shift operators
x << y Returns x with the bits shifted to the left by y places (and
new bits on the right-hand-side are zeros). This is the same as
multiplying x by 2**y.
x >> y Returns x with the bits shifted to the
right by y places. This is the same as //'ing x by 2**y.
Are "bitwise" operators.
https://wiki.python.org/moin/BitwiseOperators
>>> help("symbols")
+-------------------------------------------------+---------------------------------------+
| Operator | Description |
|=================================================|=======================================|
| "<<", ">>" | Shifts |
+-------------------------------------------------+---------------------------------------+
| "&" | Bitwise AND |
+-------------------------------------------------+---------------------------------------+
| "|" | Bitwise OR |
+-------------------------------------------------+---------------------------------------+
| "~x" | bitwise NOT |
+-----------------------------------------------------------------------------------------+
| "^" | Bitwise XOR |
+-------------------------------------------------+---------------------------------------+
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
PD: In python 3.9 the operator " | " Applied to dictionaries merges dictionaries.
https://docs.python.org/3.9/whatsnew/3.9.html
>>> x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> x | y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
>>> y | x
{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}
2 << 5 (shift to left)
Shifting 2 (in binary) 5 bits to the left. (inject zero to the right)
bin(16) # '0b10'
shifted = bin(2) + '0' * 5 # '0b1000000'
int(shifted, 2) # 64
2 << 5 # 64
1000 >> 2 (shift to right)
Shifting 1000 (in binary) 2 bits to the right. (inject zero to the left)
bin(1000) # '0b1111101000'
# add 00 to the left and remove last digit from the right
# '0b 00(add these bits) 11111010 00(remove these bits)'
shifted = '0b0011111010'
int(shifted, 2) # 250
1000 >> 2 # 250
I verified the following on both Python 2.7 and Python 3.8
I did print(100<<3)
Converting 100 to Binary gives 1100100.
What I did is I droped the first 3 bits and added 3 bits with the value '0' at the end.
So it should result as 0100000, and I converted this to Decimal and the answer was 32.
For my suprise when I executed print(100<<3) the answer was 800. I was puzzled.
I converted 800 to Binary to check whats going on.
And this is what I got 1100100000.
If you see how 800 was Python answer, they did not shift or drop the first 3 bits but they added value '0' to last 3 bits.
Where as print(100>>3) , worked perfect. I did manual calculation and cheked the print result from python. It worked correctly. Dropped last 3 bits and added value '0' to first 3 bits.
Looks like (100<<3) , left shift operator has a bug on Python.
<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
6<<2'4=6*2*2*2*2*2=64
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python - '>>' operator
There's some code that does this:
x = n - 1 >> 1
I don't know if I have to provide more syntax, but what does the >> mean? I've been searching all over, but can't find any explanation.
Its a shift right logical, it is a bitwise operation that tells the number to shift in bits by that amount. In this case you are shifting by 1, which is equivalent to dividing by 2.
If you do not understand bitwise operations, a simple conversion for you to remember would be this.
x >> n
is equivalent to
x // (2**n)
It is the bitwise shift-to-right operator.
It shifts the bits of the integer argument to the right by the number on the right-hand side of the expression:
>>> 8 >> 2
2
or illustrated in binary:
>>> bin(0b1000 >> 2)
'0b10'
Your code example is actually doubly confusing as it mixes arithmetic and bitwise operations. It should use the '//' integer division operation instead:
x = (n - 1) // 2
x >> y
is equivalent to
x.__rshift__(y)
which, as others have said, is meant to be a bitshift.
>> is the bitwise right shift operator. This operator move all bits in the first operand right by the second operand.
So: a >> b = a // 2**b
Example:
36 in binary is 0b100100
36 >> 1 is 0b10010 (last binary digit or "bit" is removed) which is 18
36 >> 2 is 0b1001 (2 bits removed) which is 9
Note that the operator goes after addition. So the code does n-1 first, then right shift it by 1 bit (i.e. divides by 2).
What does the >> operator do? For example, what does the following operation 10 >> 1 = 5 do?
It's the right bit shift operator, 'moves' all bits once to the right.
10 in binary is
1010
shifted to the right it turns to
0101
which is 5
>> and << are the Right-Shift and Left-Shift bit-operators, i.e., they alter the binary representation of the number (it can be used on other data structures as well, but Python doesn't implement that). They are defined for a class by __rshift__(self, shift) and __lshift__(self, shift).
Example:
>>> bin(10) # 10 in binary
1010
>>> 10 >> 1 # Shifting all the bits to the right and discarding the rightmost one
5
>>> bin(_) # 5 in binary - you can see the transformation clearly now
0101
>>> 10 >> 2 # Shifting all the bits right by two and discarding the two-rightmost ones
2
>>> bin(_)
0010
Shortcut: Just to perform an integer division (i.e., discard the remainder, in Python you'd implement it as //) on a number by 2 raised to the number of bits you were shifting.
>>> def rshift(no, shift = 1):
... return no // 2**shift
... # This func will now be equivalent to >> operator.
...
You can actually overloads right-shift operation(>>) yourself.
>>> class wierd(str):
... def __rshift__(self,other):
... print self, 'followed by', other
...
>>> foo = wierd('foo')
>>> bar = wierd('bar')
>>> foo>>bar
foo followed by bar
Reference: http://www.gossamer-threads.com/lists/python/python/122384
Its the right shift operator.
10 in binary is 1010 now >> 1 says to right shift by 1, effectively loosing the least significant bit to give 101, which is 5 represented in binary.
In effect it divides the number by 2.
See section 5.7 Shifting Operations in the Python Reference Manual.
They shift the first argument to the
left or right by the number of bits
given by the second argument.