Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Embedded C

Fixed-Width Types and Integer Pitfalls

Use uint8_t, int32_t and friends correctly in embedded C: integer promotion, signed/unsigned traps, overflow, saturating math and fixed-point instead of float.

In desktop C, int is "a normal number" and you rarely wonder how big it is. In embedded C, the size of a variable can be the difference between a working product and a corrupted register. On an 8-bit AVR, int is 16 bits; on a Cortex-M it is 32; on a 64-bit PC it is still 32. A hardware register that is 16 bits wide must be read as 16 bits, not as "whatever int is today".

This lesson gives you the types and habits that keep arithmetic predictable across chips: the <stdint.h> fixed-width types, the rules of integer promotion that cause surprising results, the signed/unsigned traps, saturating arithmetic, and fixed-point numbers as a replacement for floating point on small chips.

Use <stdint.h>

The header <stdint.h> defines types with exact sizes:

Type Size Range
uint8_t / int8_t 8 bits 0 to 255 / -128 to 127
uint16_t / int16_t 16 bits 0 to 65,535 / -32,768 to 32,767
uint32_t / int32_t 32 bits 0 to 4,294,967,295 / about ยฑ2.1 billion
uint64_t / int64_t 64 bits very large, but slow on 8/16/32-bit CPUs
uintptr_t pointer size holds an address as an integer
size_t pointer-ish sizes and array indices

Also available: uint_fast8_t (the fastest type with at least 8 bits, often 32 on ARM) and uint_least8_t. Use bool from <stdbool.h> (or C23's built-in bool) for truth values. Prefer fixed-width types for registers, buffers, protocol fields and anything stored in memory; the fast types are good for loop counters.

Plain char is a separate type whose signedness is implementation-defined: it is unsigned on ARM and signed on x86. Use char only for text, and uint8_t for bytes.

C How big is everything here?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Run this on the Piston runner (x86-64 Linux) and then imagine the same program on an ATmega328P: int would print 2 and long 4. Only the uintN_t rows stay the same everywhere. That is the point.

Integer promotion, again

C does arithmetic in at least int. Operands of smaller types are promoted to int first, then the result is converted back when stored. Two classic consequences:

C
uint8_t a = 200, b = 100;
uint8_t sum = a + b;      /* computed as int 300, stored as 300 & 0xFF = 44 */
if (a + b > 255) { }      /* true! the comparison happens in int */

Another: ~ on a small unsigned type.

C
uint8_t mask = 0x0F;
if (~mask == 0xF0) { }    /* false! ~mask is int 0xFFFFFFF0, not 0xF0 */

The fix is to cast or store back into the narrow type before comparing: (uint8_t)~mask == 0xF0.

C Promotion surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Signed and unsigned: the traps

Mixing signed and unsigned values in one expression converts the signed value to unsigned, which is a favorite source of bugs:

C
int  i = -1;
unsigned u = 1;
if (i < u) { /* false! -1 converted to 4294967295 */ }

And a loop that counts down with an unsigned index never ends:

C
for (uint8_t i = 10; i >= 0; i--) { }   /* i >= 0 is always true */

Rules of thumb:

  • Use unsigned types for bit patterns, register values and anything that cannot be negative.
  • Use signed types for quantities that can be negative (temperature, error, delta).
  • Never mix them in comparisons; cast one side deliberately.
  • Turn on -Wall -Wextra -Wconversion -Wsign-compare and treat warnings as errors.

Overflow: unsigned arithmetic wraps modulo 2โฟ (defined); signed overflow is undefined behavior, so the compiler may assume it never happens. A timer counter that wraps is fine as unsigned and wrong as signed.

Right-shifting and shifting too far

Shifting a value by an amount greater or equal to its width is undefined (1u << 32 on a 32-bit type). Shifting a negative signed value right is implementation-defined (usually an arithmetic shift that keeps the sign). Left-shifting 1 into the sign bit of an int (1 << 31) is undefined in C before C23; write 1u << 31 for register masks. Always use the u suffix on bit masks, and UL or ULL when you need more bits.

Saturating arithmetic

When a sensor value or an audio sample overflows, wrapping is usually the worst outcome: a loud sample suddenly becomes a negative click. Saturating arithmetic clamps at the limits instead. Many DSP chips have instructions for this; in plain C you write it yourself:

C Wrapping vs saturating addition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Fixed-point instead of floating point

Many small chips have no floating-point unit, so float math runs in software: a multiply can cost 50 to 200 cycles and pulls in kilobytes of library code. Fixed-point arithmetic stores numbers as integers with an implied binary point. In the common Q8.8 format a 16-bit value represents raw / 256, so 1.5 is stored as 384.

  • Convert: raw = (int)(x * 256), x = raw / 256.0.
  • Add and subtract: plain integer addition.
  • Multiply: (a * b) >> 8, using a wider intermediate to avoid overflow.
  • Divide: (a << 8) / b.
C Q8.8 fixed-point math

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last lines show the other classic trick: widen before you multiply ((uint32_t)adc * 3300), because adc * 3300 in 16 bits would overflow, and multiply before dividing to keep precision.

Practical rules

  1. Use uintN_t/intN_t for anything that is stored, transmitted or mapped to hardware.
  2. Add u to constants used with unsigned types: 0xFFu, 1u << 5.
  3. Cast intentionally when mixing sizes; widen before multiplying.
  4. Compare like with like; avoid unsigned loop counters that count down to zero with >= 0.
  5. Decide per variable what overflow should do (wrap, saturate, or be impossible) and document it.
  6. Prefer integers and fixed-point over float on chips without an FPU; when you use float, remember the literal 1.5 is a double and 1.5f is a float.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which type is guaranteed to be exactly 16 bits on every platform that provides it?

    Only the exact-width types of <stdint.h> have a guaranteed size; int and short vary by platform.
  2. 2. uint8_t a = 200, b = 100; what does (a + b > 255) evaluate to?

    Both operands are promoted to int, so the sum is 300, which is greater than 255.
  3. 3. Why does for (uint8_t i = 10; i >= 0; i--) never terminate?

    The condition can never be false for an unsigned type.
  4. 4. What is the main benefit of saturating arithmetic for a sensor or audio sample?

    A saturated value is still near the true value, while a wrapped one jumps to the opposite extreme.

Summary

  • Use <stdint.h> types for registers, buffers and protocols; int and long change size between chips.
  • Small operands are promoted to int before arithmetic; cast and compare carefully.
  • Mixing signed and unsigned converts to unsigned; unsigned loops that count down are a classic trap.
  • Signed overflow is undefined; unsigned wraps. Choose saturating math where wrapping is harmful.
  • On chips without an FPU, fixed-point math (Q formats) and widening before multiplying replace float.

Next: Bit Manipulation for Registers