bitwise operators - Python NOR Returning Odd Values -
i trying nor of 2 values
a = 0b1010 b = 0b0101 print(~ (a | b)) the current output -16, if hand
1010 or 0101 -------- 1111 not 1111 -------- 0000 so, should give value of 0, not -16. why this? how can fix this?
these operations being done 32-bit integers (or 64-bit integers in 64-bit version of python).
0000 0000 0000 0000 0000 0000 0000 1010 or 0000 0000 0000 0000 0000 0000 0000 0101 ------------------------------------------ 0000 0000 0000 0000 0000 0000 0000 1111 not 0000 0000 0000 0000 0000 0000 0000 1111 ------------------------------------------- 1111 1111 1111 1111 1111 1111 1111 0000 which, taken signed integer, two's complement representation of -16, because have add 16 reach 0 (and carry).
to fix it, explicitly xor 0b1111 instead of using ~.
print((a | b) ^ 0b1111)
Comments
Post a Comment