C - Bitwise Operators and Bit Manipulation in C
Bitwise operators in C allow you to perform operations directly on the binary representation (bits) of integers. These operators are very important in low-level programming, embedded systems, device drivers, networking, and performance optimization.
In C, every integer is stored in binary form (0s and 1s). Bitwise operators work on each bit individually.
1. Bitwise AND (&)
The AND operator compares each bit of two numbers.
If both bits are 1, the result is 1. Otherwise, it is 0.
Example:
int a = 5; // 0101
int b = 3; // 0011
int result = a & b; // 0001 (which is 1)
Explanation:
-
0 & 0 = 0
-
1 & 1 = 1
-
1 & 0 = 0
Common use:
-
Masking specific bits
-
Checking whether a particular bit is set
2. Bitwise OR (|)
The OR operator compares each bit.
If at least one bit is 1, the result is 1.
Example:
int a = 5; // 0101
int b = 3; // 0011
int result = a | b; // 0111 (which is 7)
Common use:
-
Setting specific bits
-
Combining flags
3. Bitwise XOR (^)
The XOR (exclusive OR) operator returns 1 only if the bits are different.
Example:
int a = 5; // 0101
int b = 3; // 0011
int result = a ^ b; // 0110 (which is 6)
Important property:
-
a ^ a = 0 -
Used in swapping numbers without a temporary variable
-
Used in encryption and error detection
4. Bitwise NOT (~)
The NOT operator inverts all bits.
0 becomes 1 and 1 becomes 0.
Example:
int a = 5; // 00000101 (8-bit example)
int result = ~a;
If using 8 bits:
-
00000101 becomes 11111010
Note:
The result depends on the number of bits used by the system (usually 32 bits for int).
5. Left Shift (<<)
The left shift operator moves bits to the left by a specified number of positions.
Example:
int a = 5; // 00000101
int result = a << 1; // 00001010 (which is 10)
Each left shift generally multiplies the number by 2.
6. Right Shift (>>)
The right shift operator moves bits to the right.
Example:
int a = 8; // 00001000
int result = a >> 1; // 00000100 (which is 4)
Each right shift generally divides the number by 2.
Practical Applications of Bit Manipulation
-
Checking if a number is even or odd:
if (num & 1)
printf("Odd");
else
printf("Even");
-
Setting a specific bit:
num = num | (1 << position);
-
Clearing a specific bit:
num = num & ~(1 << position);
-
Toggling a bit:
num = num ^ (1 << position);
Why Bitwise Operators Are Important
-
Used in embedded systems and microcontrollers
-
Efficient memory usage
-
Faster than arithmetic operations in some cases
-
Essential for implementing flags and status registers
-
Used in networking protocols and file formats
In simple terms, bitwise operators allow you to control data at the smallest level (bit level). Mastering them helps you understand how data is actually stored and manipulated inside the computer.