Skip to content
CurriculumChapter 33 · Files, Bits & Utilities
AdvancedMedium focus~14 min

Bitwise Operators & Shifts

Bitwise operators see the binary underneath every integer. They are how C talks to hardware registers, flags, permissions, and packed formats.

In plain English

Bits are tiny switches. Bitwise operators flip, combine, or inspect them.

01

AND, OR, XOR, and NOT

Bitwise AND (&) keeps a bit only when both operands have 1. OR (|) sets a bit when either operand has 1. XOR (^) sets a bit when the operands differ. NOT (~) flips every bit. These operators work independently on each bit position, which is why they are different from the logical operators &&, ||, and !.

chapter-33.cC
unsigned a = 12;  /* binary 1100 */
unsigned b = 10;  /* binary 1010 */

printf("%u\n", a & b);  /* 1000 */
printf("%u\n", a | b);  /* 1110 */
printf("%u\n", a ^ b);  /* 0110 */
printf("%u\n", ~a & 0xF); /* 0011 */
02

Left and right shift

Left shift (<<) moves bits toward the most significant end and fills with zeros. It is equivalent to multiplying by a power of two for unsigned values that do not overflow. Right shift (>>) moves bits toward the least significant end. For unsigned values it fills with zeros; for signed negative values the result is implementation-defined in older C standards, so prefer unsigned types for bit manipulation.

chapter-33.cC
unsigned x = 5;       /* 0101 */
printf("%u\n", x << 1); /* 1010 = 10 */
printf("%u\n", x >> 1); /* 0010 = 2 */

unsigned flag = 1u << 3; /* 0000 1000 */

Watch it happen

Step through the memory changes one instruction at a time.

step-by-step

Step 1 of 7

Start with two operands

a = 12 (00001100), b = 10 (00001010).

a
00001100
12 · 0x0c
b
00001010
10 · 0x0a

Key takeaways

  • Bitwise operators work on individual bits; logical operators work on truth values.
  • AND tests/clears, OR sets, XOR toggles, NOT flips.
  • Left shift multiplies by powers of two; right shift divides for unsigned values.
  • Use unsigned types for portable bit manipulation.

Common pitfalls

  • Confusing & with && and | with ||.
  • Shifting by a negative amount or by the width of the type.
  • Assuming right shift of a negative signed value is portable.

Key focus

  • Compute small bitwise expressions in binary.
  • Expect questions on shift results and operator precedence.

Quick check

0 / 2 answered

1. What is binary 1100 & binary 1010?

2. What does x << 1 do to an unsigned integer for values that do not overflow?