C ยท Chapter 38 of 45

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.

Syntax
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).

Example 1 (c)
#include <stdio.h>

int main() {
  int a = 5;   // 0101
  int b = 3;   // 0011
  printf("%d\n", a & b);
  return 0;
}
Output
1

0101 & 0011 = 0001 in binary, which is 1 in decimal.

Example 2 (c)
#include <stdio.h>

int main() {
  int a = 1;
  printf("%d\n", a << 3);
  return 0;
}
Output
8

Shifting 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.
๐Ÿ’ก Note: Don't confuse bitwise & and | with the logical && and || operators โ€” they behave very differently.

๐Ÿ“ Quick Quiz

1. What does 5 & 3 evaluate to?

2. What does 1 << 3 evaluate to?

3. Which operator flips every bit of a single value?