Bitwise Operators in C Programming (Complete Guide with Examples)


This tutorial explains bitwise operators in C, which allow performing operations directly on binary representations of integers. It covers AND, OR, XOR, NOT, left shift, and right shift operators with examples to manipulate bits efficiently.

1. What are Bitwise Operators

  1. Bitwise operators operate at the binary level on integer operands.
  2. Useful for low-level programming, embedded systems, and performance-critical applications.

2. List of Bitwise Operators

OperatorSymbolDescription
AND&Sets each bit to 1 if both bits are 1
OR``
XOR^Sets each bit to 1 if bits are different
NOT~Inverts all bits
Left Shift<<Shifts bits to left, fills 0 on right
Right Shift>>Shifts bits to right, fills 0 on left (logical)

3. Example: Bitwise AND, OR, XOR


#include <stdio.h>

int main() {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary

printf("a & b = %d\n", a & b); // 0101 & 0011 = 0001 -> 1
printf("a | b = %d\n", a | b); // 0101 | 0011 = 0111 -> 7
printf("a ^ b = %d\n", a ^ b); // 0101 ^ 0011 = 0110 -> 6
printf("~a = %d\n", ~a); // 0101 -> 1010 (two's complement) -> -6

return 0;
}

Output:


a & b = 1
a | b = 7
a ^ b = 6
~a = -6

4. Example: Left Shift and Right Shift


#include <stdio.h>

int main() {
int x = 5; // 0101 in binary

printf("x << 1 = %d\n", x << 1); // 1010 -> 10
printf("x >> 1 = %d\n", x >> 1); // 0010 -> 2

return 0;
}

Output:


x << 1 = 10
x >> 1 = 2

Explanation:

  1. << shifts bits left (multiplies by 2)
  2. >> shifts bits right (divides by 2)

5. Key Points to Remember

  1. Bitwise operators work only on integer types
  2. Useful for flags, masks, and efficient calculations
  3. &, |, ^ operate bit by bit
  4. ~ inverts bits, << and >> shift bits
  5. Essential in low-level programming, embedded systems, and networking