C Bitwise Operators
Bitwise operators work directly on the individual bits of integer values. They include & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).
Bitwise operations are common in low-level programming, such as setting hardware flags, optimizing storage, and implementing efficient algorithms.
a & b; a | b; a ^ b; ~a; a << n; a >> n;AND, OR, XOR, NOT
& sets a bit only if both operand bits are 1. | sets a bit if either operand bit is 1. ^ sets a bit if exactly one operand bit is 1. ~ flips every bit of its single operand.
Shifting bits
<< shifts bits left, filling with zeros (effectively multiplying by powers of 2). >> shifts bits right (effectively dividing by powers of 2 for unsigned/positive values).
#include <stdio.h>
int main() {
int a = 5; // 0101
int b = 3; // 0011
printf("%d\n", a & b);
return 0;
}10101 & 0011 = 0001 in binary, which is 1 in decimal.
#include <stdio.h>
int main() {
int a = 1;
printf("%d\n", a << 3);
return 0;
}8Shifting 1 left by 3 positions multiplies it by 2^3, giving 8.
Key points
- & , |, ^ and ~ perform bitwise AND, OR, XOR and NOT.
- << and >> shift bits left and right.
- Left shifting by n multiplies by 2^n; right shifting divides by 2^n.
- Bitwise operators work on the binary representation of integers.
