Reputation: 123
Small question, I'm trying to do the bitwise complement (NOT) of a signal that is 16-bit long. In Python from the documentation, I naively thought that doing the following would work:
~ x
To my surprise this returns negative numbers. I asked in a chat and they told me to use:
x ^ 65535
The thing that I still do not understand is why this works.
Why does this work?
Upvotes: 0
Views: 1178
Reputation: 2316
~x
inverts all the bits of x including its sign bit. x ^ 65535
inverts just the lower 16-bits of x.
The ^
means bitwise XOR operation. The truth table for single bit a XOR b is:
a b | a^b
---------
0 0 | 0
0 1 | 1 <-
1 0 | 1
1 1 | 0 <-
XOR has an interesting property that a ^ 0 = a
(identity) and a ^ 1 = not a
(invert). You can see this in the <-
lines in the above table.
So what x ^ 65535
(or x ^ 0xffff
which is clearer) does is bitwise XOR the lower 16 bits with 16 ones to invert just the lower 16 bits (0xffff == 65535 is 16 ones). So for a 32 bit example:
xxxx xxxx xxxx xxxx aaaa aaaa aaaa aaaa
xor 0000 0000 0000 0000 1111 1111 1111 1111
----------------------------------------------
xxxx xxxx xxxx xxxx AAAA AAAA AAAA AAAA (where A is ~a)
The x's represent bits that remain the same in the input and result. The A's represent bits that have been inverted.
BTW: another way to do the same thing would have been:
~x & 0xffff
Upvotes: 6