How to Use Bitwise NOT Operator in C: Syntax and Examples
In C, the bitwise NOT operator is
~. It flips every bit of an integer value, turning 0s into 1s and 1s into 0s. Use it by placing ~ before an integer variable or value, like ~x.Syntax
The bitwise NOT operator in C is a unary operator represented by ~. It takes one integer operand and returns the bitwise complement of that operand.
- ~operand: Flips all bits of
operand. operandmust be an integer type (int, char, long, etc.).
c
~x
Example
This example shows how ~ flips bits of an integer. It prints the original number and its bitwise NOT result.
c
#include <stdio.h> int main() { unsigned int x = 5; // binary: 00000000 00000000 00000000 00000101 unsigned int result = ~x; printf("Original x: %u\n", x); printf("Bitwise NOT ~x: %u\n", result); return 0; }
Output
Original x: 5
Bitwise NOT ~x: 4294967290
Common Pitfalls
Common mistakes when using ~ include:
- Using signed integers without understanding two's complement representation, which can cause unexpected negative results.
- Confusing bitwise NOT
~with logical NOT!. - Not considering the size of the integer type, which affects the number of bits flipped.
Always use unsigned types if you want predictable bit-flipping results.
c
#include <stdio.h> int main() { int x = 5; int wrong = !x; // Logical NOT, not bitwise int right = ~x; // Bitwise NOT printf("Logical NOT !x: %d\n", wrong); printf("Bitwise NOT ~x: %d\n", right); return 0; }
Output
Logical NOT !x: 0
Bitwise NOT ~x: -6
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| ~ | Bitwise NOT (flips bits) | ~5 | Depends on int size, e.g. -6 for signed int |
| ! | Logical NOT (true/false) | !5 | 0 (false) |
| & | Bitwise AND | 5 & 3 | 1 |
| | | Bitwise OR | 5 | 3 | 7 |
| ^ | Bitwise XOR | 5 ^ 3 | 6 |
Key Takeaways
Use the ~ operator to flip all bits of an integer in C.
Prefer unsigned integers with ~ for predictable results.
Do not confuse bitwise NOT (~) with logical NOT (!).
The result depends on the integer size and signedness.
Print results carefully to understand bitwise operations.