C Bitwise Operators
In C, bitwise operators allow manipulation of individual bits within an integer value. These operators perform operations at the binary level, making them useful for tasks such as setting flags, optimizing performance, and low-level programming.
Bitwise operators include AND, OR, XOR, NOT, left shift, and right shift.
Bitwise Operators in C
The following table lists the bitwise operators available in C:
Operator Name | Operator Symbol | Description |
---|---|---|
Bitwise AND | & | Performs bitwise AND operation. A bit is set to 1 only if both corresponding bits are 1. |
Bitwise OR | | | Performs bitwise OR operation. A bit is set to 1 if at least one corresponding bit is 1. |
Bitwise XOR | ^ | Performs bitwise XOR operation. A bit is set to 1 if corresponding bits are different. |
Bitwise NOT or Bitwise Complement | ~ | Inverts all bits (one’s complement). |
Left Shift | << | Shifts bits to the left by a specified number of positions, filling with zeros. |
Right Shift | >> | Shifts bits to the right by a specified number of positions. The behavior depends on the sign of the number. |
Examples of Bitwise Operators
1. Bitwise AND Operator
In this example, we use the bitwise AND &
operator to compare two binary values.
main.c
#include <stdio.h>
int main() {
int a = 5, b = 3;
int result = a & b;
printf("Bitwise AND of %d and %d is %d\n", a, b, result);
return 0;
}
Explanation:
- Binary representation of 5:
0101
- Binary representation of 3:
0011
- Bitwise AND operation:
0101 & 0011 = 0001
(Decimal 1)
Output:
Bitwise AND of 5 and 3 is 1
2. Bitwise OR Operator
In this example, we use the bitwise OR |
operator to compare two binary values.
main.c
#include <stdio.h>
int main() {
int a = 5, b = 3;
int result = a | b;
printf("Bitwise OR of %d and %d is %d\n", a, b, result);
return 0;
}
Explanation:
- Binary representation of 5:
0101
- Binary representation of 3:
0011
- Bitwise OR operation:
0101 | 0011 = 0111
(Decimal 7)
Output:
Bitwise OR of 5 and 3 is 7
3. Bitwise Left Shift Operator
In this example, we use the left shift <<
operator to shift bits to the left.
main.c
#include <stdio.h>
int main() {
int a = 5;
int result = a << 1;
printf("Left shift of %d by 1 is %d\n", a, result);
return 0;
}
Explanation:
- Binary representation of 5:
0101
- Left shift by 1:
1010
(Decimal 10) - Each bit moves one position to the left, filling with 0.
Output:
Left shift of 5 by 1 is 10
Conclusion
In this tutorial, we explored C bitwise operators:
- Bitwise operators manipulate individual bits of integer values.
- The common operators include AND, OR, XOR, NOT, left shift, and right shift.
- They are useful in low-level programming, bit masking, and optimizing performance.
Understanding bitwise operators is essential for efficient programming in embedded systems, cryptography, and optimization techniques.