Bitwise Operators in C
Bitwise operators in C perform operations directly on the binary
representation of integers. They are extremely fast and commonly used in
embedded systems, cryptography, digital electronics, optimization, and
low-level programming.
What Are Bitwise Operators?
Bitwise operators treat data as a collection of bits (0s and 1s). Instead of working on whole numbers, they manipulate individual bits.
- Very fast (used in performance-critical code)
- Operate only on integers
- Useful in flags, masks, drivers, hardware control
List of Bitwise Operators
& β Bitwise AND | β Bitwise OR ^ β Bitwise XOR ~ β Bitwise NOT (Oneβs complement) << β Left Shift >> β Right Shift
1. Bitwise AND (&)
Sets a bit to 1 only if both bits are 1.
10 & 7 1010 0111 ---- 0010 (2)
2. Bitwise OR (|)
Sets a bit to 1 if any one of the bits is 1.
10 | 5 1010 0101 ---- 1111 (15)
3. Bitwise XOR (^)
Sets bit to 1 if bits are different.
10 ^ 5 1010 0101 ---- 1111 (15)
4. Bitwise NOT (~)
Flips every bit (0 β 1, 1 β 0).
~5 00000101 11111010 ( -6 ) // twoβs complement
5. Left Shift (<<)
Shifts bits left and fills 0 on the right.
5 << 2 00000101 00010100 (20)
6. Right Shift (>>)
Shifts bits right and fills MSB depending on sign.
20 >> 2 00010100 00000101 (5)
Practical Example β All Bitwise Operators
#include <stdio.h>
int main() {
int a = 10, b = 5;
printf("AND: %d\n", a & b);
printf("OR: %d\n", a | b);
printf("XOR: %d\n", a ^ b);
printf("NOT: %d\n", ~a);
printf("Left Shift: %d\n", a << 1);
printf("Right Shift: %d\n", a >> 1);
return 0;
}
Useful Real-Life Uses
- Setting or clearing specific bits
- Creating flags & masks
- Checking odd/even (n & 1)
- Fast multiplication/division by 2 (<<, >>)
- Cryptography & hashing
- Microcontroller programming
Practice Questions
- Explain bitwise XOR with an example.
- Why are bitwise operators used in embedded systems?
- What does a << 3 mean?
- Write differences between AND, OR, XOR.
- Write a program to count set bits in a number.
Practice Task
Write a program to toggle the 3rd bit of any given number
(using XOR) and print the result.