I am trying to get a NOR of 2 values
a = 0b1010
b = 0b0101
print(~ (a | b))
The current output is -16
, but if I do this by hand
1010
OR 0101
--------
1111
NOT 1111
--------
0000
So, this should give a value of 0
, not -16
. Why does it do this? How can I fix this?
These operations are being done with 32-bit integers (or 64-bit integers in a 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 as a signed integer, is the two's complement representation of -16, because you have to add 16 to reach zero (and a carry).
To fix it, explicitly xor with 0b1111
instead of using ~
.
print((a | b) ^ 0b1111)