Bitwise NOT and One's Complement
Understand the NOT (~) operator that flips every bit. Learn about one's complement, two's complement, and how NOT relates to negation in binary.
Detailed Explanation
Understanding Bitwise NOT (~)
NOT is a unary operator — it takes a single operand and flips every bit: 0 becomes 1, and 1 becomes 0. The result is called the one's complement of the original value.
Truth Table
A | ~A
--|----
0 | 1
1 | 0
Worked Example (8-bit)
42 = 00101010
~42 = 11010101 (213 unsigned, -43 signed)
One's Complement vs. Two's Complement
In a signed integer system using two's complement (which virtually all modern CPUs use), the relationship between NOT and negation is:
~A = -(A + 1)
So ~42 = -43, ~0 = -1, and ~(-1) = 0. This identity is useful for:
- Computing
-(A + 1)without addition - Creating bitmasks:
~0produces all 1s (0xFFFFFFFF in 32-bit) - Inverting a mask:
~maskgives the complement mask for clearing bits
Practical Patterns
Clear bits with AND + NOT:
// Clear bit 3 of value
value = value & ~(1 << 3);
Create a mask for the upper N bits:
// Mask for upper 4 bits of a byte
const mask = ~0x0F & 0xFF; // 0xF0
Width Sensitivity
The result of NOT depends on the bit width. ~42 in 8-bit is 213 (unsigned) or -43 (signed), but in 32-bit it is 4294967253 (unsigned) or still -43 (signed). Always be aware of your integer width when using NOT.
Use Case
Systems programmers use NOT to create complement masks for clearing bits in hardware registers. For example, to disable a specific interrupt on a microcontroller, you read the interrupt enable register, AND it with the NOT of the interrupt's bit mask, and write it back: REG = REG & ~INT_MASK. This clears only the target bit while preserving all other interrupt settings.