The bitwise NOT operator flips all the bits in an 8-bit number. Hence, 0 becomes 1, and 1 becomes 0. It is represented by the tilde symbol (~
).
Note: For binary representations of integers where the number of bits are less than 8, we add extra 0's to the left such that the number of bits equal a multiple of 8.
~NUM
Bitwise NOT is a prefix operator and appears immediately before any NUM
.
The bitwise NOT operator returns 1 when the bit is 0, and 0 when the bit is 1. In other words, for any integer ~
on different bits are summarized below:
NUM | ~NUM |
1 | 0 |
0 | 1 |
The code that defines the NOT operator is as follows:
// declare an integer variablevar number = 10 // binary: 00001010// perform bitwise NOT operationvar resultNumber = ~numberprint(resultNumber) // -11 , binary: 11110101// The answer is supported by the following// calculation as well:// -(10+1) = -11
The explanation of the above code is as follows:
number
, and assign it the integer value 10 (00001010 in binary).number
is traversed bitwise, and the resulting bit is set to 1 if the bit is 0. Otherwise, it is set to 0. We store the final answer in the resultNumber
variable. The complete calculation is shown below:To convert a binary into a negative decimal, the left-most bit represents the sign (negative if 1 and positive if 0). In the example above, the left-most bit is 1 so the answer is a negative value. The calculation is shown below:
Free Resources