How to Use Bitwise Operators in C: Syntax and Examples
In C, bitwise operators like
&, |, ^, ~, <<, and >> manipulate individual bits of integers. Use them to perform operations such as AND, OR, XOR, NOT, left shift, and right shift directly on binary representations.Syntax
Bitwise operators work on integer types and manipulate bits directly:
&: Bitwise AND|: Bitwise OR^: Bitwise XOR (exclusive OR)~: Bitwise NOT (inverts bits)<<: Left shift (shifts bits left)>>: Right shift (shifts bits right)
Operands are integers, and the result is an integer with bits changed accordingly.
c
result = a & b; // Bitwise AND result = a | b; // Bitwise OR result = a ^ b; // Bitwise XOR result = ~a; // Bitwise NOT result = a << 2; // Left shift by 2 bits result = a >> 3; // Right shift by 3 bits
Example
This example shows how to use bitwise operators to combine and modify bits of two numbers.
c
#include <stdio.h> int main() { unsigned int a = 5; // binary: 0101 unsigned int b = 9; // binary: 1001 printf("a & b = %u\n", a & b); // AND printf("a | b = %u\n", a | b); // OR printf("a ^ b = %u\n", a ^ b); // XOR printf("~a = %u\n", ~a); // NOT printf("a << 1 = %u\n", a << 1); // Left shift printf("b >> 2 = %u\n", b >> 2); // Right shift return 0; }
Output
a & b = 1
a | b = 13
a ^ b = 12
~a = 4294967290
a << 1 = 10
b >> 2 = 2
Common Pitfalls
Common mistakes when using bitwise operators include:
- Using bitwise operators instead of logical operators (
&&,||) for conditions. - Not considering signed vs unsigned types, which affects shifts and
~results. - Shifting bits by a value equal or larger than the bit width (e.g., shifting 32 bits on a 32-bit int).
- Forgetting operator precedence, which can cause unexpected results without parentheses.
c
#include <stdio.h> int main() { int x = 4; // 0100 int y = 2; // 0010 // Wrong: using bitwise AND instead of logical AND if (x & y) { printf("Bitwise AND used in condition: true\n"); } // Right: use logical AND if (x && y) { printf("Logical AND used in condition: true\n"); } return 0; }
Output
Bitwise AND used in condition: true
Logical AND used in condition: true
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| & | Bitwise AND | 5 & 3 | 1 (0101 & 0011 = 0001) |
| | | Bitwise OR | 5 | 3 | 7 (0101 | 0011 = 0111) |
| ^ | Bitwise XOR | 5 ^ 3 | 6 (0101 ^ 0011 = 0110) |
| ~ | Bitwise NOT | ~5 | 4294967290 (inverts bits) |
| << | Left shift | 5 << 1 | 10 (0101 << 1 = 1010) |
| >> | Right shift | 5 >> 1 | 2 (0101 >> 1 = 0010) |
Key Takeaways
Bitwise operators manipulate individual bits of integers for efficient low-level operations.
Use & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift) with integer types.
Avoid confusing bitwise operators with logical operators in conditions.
Be careful with signed vs unsigned types and shift amounts to prevent unexpected results.
Use parentheses to ensure correct operator precedence when combining bitwise operations.