What adds '=' to bitwise operators in Python? (i.e. "<< =" instead of "<<")

What do the <<= and |= Python operators mean? I assume these are bitwise operators. I know the operators | (bitwise or) and << (bit offset), but I do not know them in combination with = .

I found it in this piece of code. Below is the code below.

 commandout = adcnum commandout |= 0x18 # start bit + single-ended bit commandout <<= 3 # we only need to send 5 bits here for i in range(5): if (commandout & 0x80): GPIO.output(mosipin, True) else: GPIO.output(mosipin, False) commandout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) 
+4
source share
2 answers

Both are assigned locally; they effectively give you name = name op right-hand-expression in space only name op= right-hand-expression .

So, for your example, you can read this as:

 commandout = commandout | 0x18 commandout = commandout << 3 

This simplifies it a bit, because with the hooks allocated for these operations, the left object can select something special; list += rhs really list.extend(rhs) , for example, not list = list + rhs . The in-place statement gives the mutable object the ability to apply the change to self instead of creating a new object.

In your example, however, where I assume that commandout is int, you have immutable values, and the in-place operation should return a new value.

+8
source

These are the operators of bit arithmetic operations. They change the LH value in place (or reassign the lh value of the new calculated value if lh is unchanged) with the same style operators as C.

Python calls them operator transfers ( << and >> ) and binary bitwise operators ( & , ^ and | ).

With the addition of = after the statement, the assignment returns to the original name LH, so |= does in place or and <<= performs a left shift in place.

So, x<<=3 coincides with x=x<<3 or the value of bit x is shifted to the left by 3 places.

Shift Bit:

 >>> b=0x1 >>> b<<=3 >>> bin(b) '0b1000' >>> b>>=2 >>> bin(b) '0b10' 

Bit or:

 >>> bin(b) '0b1' >>> bin(c) '0b100' >>> c|=b >>> bin(c) '0b101' 

Technically, if the LH value is unchanged, the result is a rebound to the LH name, rather than the actual conversion of the value in place.

This can be shown by examining this element address:

 >>> id(i) 4298178680 # original address (in CPython, id is the address) >>> i<<=3 >>> id(i) 4298178512 # New id; new int object created 

Unlike using C (in this case, ctypes ):

 >>> import ctypes >>> i=ctypes.c_int(1) >>> ctypes.addressof(i) 4299577040 >>> i.value<<=3 >>> ctypes.addressof(i) 4299577040 

Since C integers are mutable, the bit shift is performed in place without a new address for C int.

+2
source

All Articles