NOT is unlike the other bitwise operators in that it does not perform an operation on two bitfields. It only performs an operation on one. What it does is reverse the bitfield; if a bit was previously 0, it is changed to 1, and vice versa.
Truth Table:
NOT | |
1 | 0 |
0 | 1 |
Usage:
// A bitfield whose binary representation is: 00000000000000000000000000001010 integer a = 10; // Another bitfield whose binary representation is: 00000000000000000000000000011001 integer b = 25; // The next line translates to "store the result of OR'ing a and b together" in the variable a_OR_b. // Its binary representation is 00000000000000000000000000011011, or 27. integer a_OR_b = a | b;
Here is that operation written out longwise:
a 00000000000000000000000000001010 // As decimal = 10 ----------------------------------------------------------------------- ~a 11111111111111111111111111110101 // As decimal = -11
NOT is commonly used to set bits to 0 in bitfields. To do this, a bit is NOTed to get ~bit. The bitfield is then ANDed with the ~bit.
For example, lets say you wanted to turn off 00000000000000000000000000000010 (2 in decimal) in the bitfield 00000000000000000000000000011010 (26 in decimal).
First you’d get ~00000000000000000000000000000010, which is 11111111111111111111111111111101 (-3 in decimal) then you’d AND ~2 and 26. Here is this in code:
integer bitfield = 26; integer bit = 2; bitfield = bitfield & ~bit;
Here are the operations written out longwise:
2 00000000000000000000000000000010 ----------------------------------------------------------------------- ~2 11111111111111111111111111111101 // As decimal = -3 26 00000000000000000000000000011010 ~2 11111111111111111111111111111101 ----------------------------------------------------------------------- 26 & ~2 00000000000000000000000000011000 // As decimal = 24