Skip to content

ProgrammingC on a Microcontroller

Integers, Overflow and Bit Masks

An 8-bit unsigned number wraps from 255 to 0; masks set, clear and test single bits.

Not started Jump to practice

On a small microcontroller, programs are often written in C or C++ (an Arduino sketch is C++). Numbers there have fixed sizes, and that causes some of the most confusing bugs in robotics.

Key idea

An 8-bit unsigned integer (uint8_t) holds 0 to 255; adding past 255 wraps around to 0. A 16-bit unsigned one holds 0 to 65,535. Bit masks work on single bits: x | (1 << n) sets bit $n$, x & ~(1 << n) clears it, and x & (1 << n) tests it.

Worked example: Overflow

A uint8_t holds 250. The program adds 10. What does it hold?
  1. $250 + 10 = 260$.
  2. 260 is more than 255, so it wraps: $260 - 256 = 4$.

Answer: 4.

Worked example: Set a bit

A register holds binary 0000 0101 (5). Set bit 3.
  1. 1 << 3 is 0000 1000 (8).
  2. OR them: 0000 1101.

Answer: 13.

Why it works

Encoder counts, timers and sensor registers all live in fixed-size integers. A robot whose distance suddenly jumps from 32,767 to βˆ’32,768 has hit a 16-bit signed overflow, not a broken sensor. Hardware registers pack many on-off settings into one byte, so bit masks are how you change one without disturbing the rest.

Common mistake

Expecting 250 + 10 to be 260 in an 8-bit variable, or clearing a bit with OR. OR can only set bits; to clear one, AND with the mask's complement.
Our Homeschool Code Practice page drills binary and hexadecimal, the number bases these masks are written in.

Practice

Pass with 3 right answers, the last 2 in a row. Each right answer earns 3 XP.

Loading practice…

Builds on

Leads to

Sources and further reading

  • Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, 2nd ed. (Prentice Hall, 1988)
  • Arduino Documentation