How does bitwise 'or' becomes a '+=' in bytecode for python

92 views Asked by At

I was reading the following explanation of python bytecode. I'm posting a lot in order to give the full context. I'm confused about the part where the bitwise 'or' becomes a '+='.

EXTENDED_ARG 1
CALL_FUNCTION 4

When the interpreter executes EXTENDED_ARG, its oparg (which is 1) is left-shifted by eight bits and stored in a temporary variable. Let’s call it extended_arg (do not confuse it with the opname EXTENDED_ARG):

extened_arg = 1 << 8  # same as 1 * 256

So the binary value 0b1 (the binary value of 1) is converted to 0b100000000. This is like multiplying 1 by 256 in the decimal system and extened_arg will be equal to 256. Now we have two bytes in extened_arg. When the interpreter reaches to the next instruction, this two-byte value is added to its oparg (which is 4 here) using a bitwise or.

extened_arg = extened_arg | 4
# Same as extened_arg += 4

This is like adding the value of the oparg to extened_arg. So now we have:

extened_arg = 256 + 4 = 260

and this value will be used as the actual oparg of CALL_FUNCTION. So, in fact,

EXTENDED_ARG 1
CALL_FUNCTION 4

is interpreted as:

EXTENDED_ARG 1
CALL_FUNCTION 260

Can someone explain how this translates.

3

There are 3 answers

4
user2357112 On

If x and y share no set bits, then x | y is equivalent to x + y.

1
Nine Tails On
  • step 1 : 1 << 8 this is equal to 100000000.
    Which is 256 in decimal

  • step 2: now 256 + 4 = 260. (obviously)
    256|4 is same as 100000000|100 = 100000100 = 260. (check how bitwise operators work)


from the above 2 statements the author concluded that += is same as |

note about or operator:
if you want to find the result of ORing to operands, just line them up, like you do when you add 2 numbers, then look at each pair of bits from right to left and if there is at least one 1 bit then the resulting number will have a 1 bit too, otherwise it is a 0.

0
VPfB On

If one of the operands is known to be zero, then 0 + bit = bit gives the same result as 0 | bit == bit, where bit is 0 or 1.