Lesson 47 +10 XP

Bitwise Operators

Bitwise Operators

Numbers live inside the computer as bits: 0 and 1. Bitwise operators work directly on those bits.

Binary look at a number

5 is 00000101 in binary (8 bits).

The six bitwise operators

  • & AND: 1 only when both bits are 1.
  • | OR: 1 when at least one bit is 1.
  • ^ XOR: 1 when the bits differ.
  • ~ NOT: flips every bit.
  • << shift left: move the bits left.
  • >> shift right: move the bits right.

A small program

printf("%d\n", 6 & 3);   // 2
printf("%d\n", 6 | 3);   // 7
printf("%d\n", 6 ^ 3);   // 5
printf("%d\n", 1 << 3);  // 8

Shifts: quick multiplication and division

Moving bits left by one doubles the number; moving right by one halves it. 1 << 3 gives 8.

Common uses

  • x & 1 tests if a number is even or odd.
  • Shifts are fast ways to multiply/divide by powers of 2.
  • Flags and packing multiple settings into one int.

TL;DR

  • Bitwise ops: &, |, ^, ~, <<, >>.
  • << shifts left, >> shifts right.
  • 6 in binary is 110.
  • 1 << n equals 2^n.