How Bitwise NOT Inverts Binary Values
The bitwise NOT operator is a fundamental unary operation in computer science that flips every individual bit of a binary number, transforming zeros into ones and ones into zeros. This article explains how the bitwise NOT operation functions at the binary level, the rules of bit-level logic that govern it, and how it translates into negative values when applied to signed integers through two's complement representation.
The Basic Logic of Bitwise Inversion
At its core, the bitwise NOT operation (often denoted by the tilde
~ symbol) acts upon a single binary input. Unlike binary
operators such as AND or OR, which compare two numbers, NOT evaluates
each bit position individually.
The rule for the bitwise NOT operation is strictly defined by a simple truth table:
- An input bit of
0becomes1. - An input bit of
1becomes0.
For example, when applied to an unsigned 8-bit integer:
- Original binary:
00001100(decimal 12) - Inverted binary:
11110011(decimal 243)
Each position is independently toggled, resulting in the exact logical complement of the original value, also known as the one's complement.
Bitwise NOT and Two's Complement Representation
In most modern computer systems, integers are stored as signed values
using two's complement notation. In two's complement, the most
significant bit (the leftmost bit) serves as the sign bit:
0 represents a positive number or zero, and 1
represents a negative number.
When the bitwise NOT operation is applied to a signed number:
- The sign bit flips. A positive number becomes negative, and a negative number becomes positive.
- In two's complement arithmetic, the mathematical negative of a number \(x\) is defined as \(-x = \sim x + 1\).
- Rearranging this formula demonstrates what happens during a NOT operation: \(\sim x = -(x + 1)\).
Step-by-Step Example
Consider the 8-bit signed integer 5:
- The binary representation of
5is00000101. - Applying the bitwise NOT flips all bits:
11111010. - Because the leading bit is
1, the result is a negative number in two's complement. - To find its decimal value, determine the two's complement magnitude:
invert the bits (
00000101) and add1(00000110, which is6). - Applying the negative sign gives
-6.
Thus, ~5 evaluates directly to -6.
Practical Uses of the Bitwise NOT
Understanding how bitwise NOT inverts binary values is crucial for several low-level operations:
- Bitmasking: Inverting masks to clear specific bits
in a register without altering others (e.g., using
x & ~mask). - Flags Management: Toggling states or resetting permission bits in system configurations.
- Fast Sign Manipulation: Quickly calculating relative negative offsets in assembly and systems programming.