Bitwise operators are used to perform operations on individual bits of integer data types (char, int, long). They are essential in embedded systems, cryptography, and network programming where direct hardware manipulation or high optimization is required.
| Operator | Name | Description |
|---|---|---|
& |
AND | Sets bit to 1 if both corresponding bits are 1. |
| |
OR | Sets bit to 1 if at least one corresponding bit is 1. |
^ |
XOR | Sets bit to 1 if only one of the corresponding bits is 1. |
~ |
NOT | Inverts all bits (0 becomes 1, 1 becomes 0). |
<< |
Left Shift | Shifts bits to the left, filling with zeros. (Multiplies by 2) |
>> |
Right Shift | Shifts bits to the right. (Divides by 2) |
Let's see these operators in action. Assume we are dealing with 8-bit integers for simplicity.
A = 12 (Binary: 0000 1100)
B = 25 (Binary: 0001 1001)
#include <stdio.h>int main() { int a = 12; // 00001100 int b = 25; // 00011001 printf("a & b = %d\n", a & b); // AND: 00001000 (8) printf("a | b = %d\n", a | b); // OR: 00011101 (29) printf("a ^ b = %d\n", a ^ b); // XOR: 00010101 (21) printf("~a = %d\n", ~a); // NOT: 11110011 (-13) printf("a << 1 = %d\n", a << 1); // Left Shift: 00011000 (24) printf("a >> 1 = %d\n", a >> 1); // Right Shift: 00000110 (6) return 0; }
Bitwise operators are frequently used for Bit Masking—the act of setting, clearing, or toggling specific bits in a register without affecting the others.
FLAG |= (1 << n);FLAG &= ~(1 << n);FLAG ^= (1 << n);if (FLAG & (1 << n))Which operator is used to perform a Bitwise XOR operation in C?