Reputation: 11461
What do the <<=
and the |=
operators mean Python? I guess they are bitwise operators. I know the operators |
(bitwise or) and <<
(bit shifting), but I don't know them in combination with the =
.
I found it in this piece code. Code below belongs to that code.
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)
Upvotes: 4
Views: 250
Reputation: 103754
Those are in place bit arithmetic operators. They modify the LH value in place (or reassign the lh value the new calculated value if the lh is immutable) with the same style operators as C.
Python calls them shifting operators (<<
and >>
) and binary bit operators (&
,^
and |
).
With the addition of the =
after the operator, the assignment is back to the original LH name, so |=
does an in place or
and <<=
does an in-place left shift.
So x<<=3
is the same as x=x<<3
or the value of x bit shifted to the left 3 places.
Bit shift:
>>> 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 immutable, the result is rebound to the LH name rather than an actual in-place transformation of the value.
This can be shown by examining that address of item:
>>> 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 done in place with no new address for the C int.
Upvotes: 2
Reputation: 1121494
Both are in-place assignments; they effectively give you name = name op right-hand-expression
in the space of just name op= right-hand-expression
.
So for your example, you could read that as:
commandout = commandout | 0x18
commandout = commandout << 3
That is oversimplifying it a little, because with dedicated hooks for these operations the left-hand-side object can choose to do something special; list += rhs
is really list.extend(rhs)
for example, not list = list + rhs
. An in-place operator gives a mutable object the chance to apply the change to self
instead of creating a new object.
For your example, however, where I presume commandout
is an int, you have immutable values and the in-place operation has to return a new value.
Upvotes: 8