tslnc04 - 1 year ago 69

Python Question

I am trying to get a NOR of 2 values

`a = 0b1010`

b = 0b0101

print(~ (a | b))

The current output is

`-16`

`1010`

OR 0101

--------

1111

NOT 1111

--------

0000

So, this should give a value of

`0`

`-16`

Answer Source

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)
```