Try Embedded

Integers and data types

Fixed-width types, integer promotion, overflow and the signed/unsigned rules that bite.

Why firmware uses fixed-width types

The C standard only promises minimum sizes. int is 16 bits on an 8-bit AVR and 32 bits on a Cortex-M, and long is 32 bits on a Cortex-M but 64 bits on a Linux PC. A register that is exactly 16 bits wide, or a protocol field that is exactly 4 bytes, cannot be described with a type whose size depends on the compiler.

<stdint.h> fixes that. Use uint8_t, int16_t, uint32_t and friends whenever the width matters, which in firmware is most of the time.

Type8-bit AVR32-bit Cortex-M64-bit PC (Linux)
char111
short222
int244
long448
long long888
pointer248

The examples on this page run on a simulated 32-bit little-endian microcontroller, so they print what a Cortex-M would.

#include <stdio.h>
#include <stdint.h>

int main(void) {
  printf("char=%u short=%u int=%u long=%u long long=%u pointer=%u\n",
         (unsigned)sizeof(char), (unsigned)sizeof(short), (unsigned)sizeof(int),
         (unsigned)sizeof(long), (unsigned)sizeof(long long), (unsigned)sizeof(void *));
  printf("uint8_t max=%u  int16_t min=%d  uint32_t max=%u\n", UINT8_MAX, INT16_MIN, UINT32_MAX);
  return 0;
}

Note: Whether plain char is signed is also up to the platform. It is signed on x86 and unsigned in the Arm ABI. Use uint8_t for bytes and char only for text.

Integer promotion

C never does arithmetic in a type narrower than int. Before almost any operator is applied, uint8_t, int8_t, uint16_t and int16_t operands are converted to int. This is called integer promotion, and it explains most surprising results with small types.

#include <stdio.h>
#include <stdint.h>

int main(void) {
  uint8_t a = 200, b = 100;
  uint8_t stored = a + b;        // the sum is 300 as an int, then truncated to 8 bits

  printf("a + b as an int: %d\n", a + b);
  printf("stored in a uint8_t: %u\n", stored);

  uint8_t x = 0xF0;
  printf("~x is 0x%X, not 0x0F\n", ~x);          // x was promoted to a 32-bit int first
  printf("(uint8_t)~x is 0x%02X\n", (uint8_t)~x);
  return 0;
}

Two consequences are worth memorising:

  • Truncation happens at the assignment, not at the operator. a + b > 255 can be true even though both are uint8_t.
  • ~x == 0x0F is never true for a uint8_t x, because ~x has the upper 24 bits set. Cast the result back: (uint8_t)~x.

Mixing signed and unsigned

When the two operands of an operator have different types, C converts both to a common type. If one is unsigned int and the other is int, the common type is unsigned int, so the signed value is reinterpreted. A negative number becomes a very large positive one.

#include <stdio.h>
#include <stdint.h>

int main(void) {
  int32_t temperature = -1;
  uint32_t limit = 10;

  if (temperature < limit) printf("below the limit\n");
  else printf("NOT below the limit: -1 was converted to %u\n", (uint32_t)temperature);
  return 0;
}

The run shows a warning for the comparison, the same one GCC gives with -Wsign-compare. Turn that warning on in real projects.

Pitfall: for (uint8_t i = 10; i >= 0; i--) never ends. An unsigned value is always >= 0, and decrementing 0 wraps to 255.

What happens on overflow

The rules differ by type, and the difference matters because compilers exploit it.

SituationResult
Unsigned arithmetic overflowsDefined: wraps modulo 2^N
Signed arithmetic overflowsUndefined behaviour
Out-of-range value converted to an unsigned typeDefined: wraps modulo 2^N
Out-of-range value converted to a signed typeImplementation-defined (wraps on every mainstream compiler)
Shift by a negative count, or by the width of the type or moreUndefined behaviour
Division by zeroUndefined behaviour

"Undefined" does not mean "wraps on my board". It means the optimiser may assume it never happens, and delete code that only matters if it does. A check written as if (a + b < a) for signed values is routinely removed at -O2.

The safe pattern is to check before the operation:

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

// Unsigned: wrap-around is well defined, so it can be detected after the fact.
static bool add_u32(uint32_t a, uint32_t b, uint32_t *sum) {
  *sum = a + b;
  return *sum >= a;              // false if the addition wrapped
}

// Signed: the check has to come first.
static bool add_i32(int32_t a, int32_t b, int32_t *sum) {
  if (b > 0 && a > INT32_MAX - b) return false;
  if (b < 0 && a < INT32_MIN - b) return false;
  *sum = a + b;
  return true;
}

int main(void) {
  uint32_t u;
  int32_t s = 0;
  printf("%d %u\n", add_u32(4000000000u, 500000000u, &u), u);
  printf("%d %d\n", add_i32(INT32_MAX, 1, &s), s);
  printf("%d %d\n", add_i32(-5, 3, &s), s);
  return 0;
}

Constants have types too

An unsuffixed constant such as 1 is an int. That matters in two common places.

  • 1 << 31 shifts a 1 into the sign bit of an int, which is undefined. Write 1u << 31.
  • On a 16-bit target, 60 * 1000 overflows because both constants are 16-bit ints. Write 60UL * 1000.
SuffixTypeExample
noneint (or wider if the value needs it)100
uunsigned int1u << 31
l, ullong, unsigned long60UL * 1000
ll, ulllong long, unsigned long long1ULL << 40

Multiply before you divide to keep precision, and make sure the intermediate result fits:

#include <stdio.h>
#include <stdint.h>

int main(void) {
  uint16_t raw = 3000;                              // 12-bit ADC reading
  uint32_t wrong = raw / 4095 * 3300;               // the division gives 0 first
  uint32_t right = (uint32_t)raw * 3300 / 4095;     // widen, multiply, then divide
  printf("divide first: %u mV, multiply first: %u mV\n", wrong, right);
  return 0;
}

Common mistakes

  • Using int for a value that must be exactly 8, 16 or 32 bits.
  • Comparing a signed variable with sizeof, strlen or any other unsigned value.
  • Assuming a uint8_t expression stays 8 bits wide in the middle of a calculation.
  • Printing a 64-bit value with %d. Use %lld, or the PRId64 macros from <inttypes.h>.
  • Relying on signed overflow wrapping, or on 1 << 31.

Interview question: Why does embedded code use uint32_t instead of unsigned long?

Answer: Because the width is part of the meaning. A hardware register or a protocol field has a fixed number of bits, while unsigned long is 32 bits on a Cortex-M and 64 bits on a 64-bit Linux build of the same code. Fixed-width types make the code portable between targets and make host-side unit tests behave like the device.

Interview question: What is the difference between undefined and implementation-defined behaviour?

Answer: Implementation-defined means the compiler must pick a behaviour and document it, for example the result of right-shifting a negative number. Undefined means the standard places no requirement at all, so the compiler may assume the situation never occurs and optimise on that assumption. Signed overflow, out-of-range shifts and out-of-bounds access are undefined.

In the product: an industrial energy meter

A meter adds the energy used every second, for years. Choose the counter's type wrongly and the total wraps round to zero, and so does the bill.

#include <stdio.h>
#include <stdint.h>

int main(void) {
  uint16_t small = 65000;      // a counter that is too small
  uint32_t big = 65000;
  for (int second = 0; second < 1000; second++) {
    small += 1;                // 1 Wh a second
    big += 1;
  }
  printf("uint16_t total: %u Wh\n", small);   // wrapped round
  printf("uint32_t total: %lu Wh\n", (unsigned long)big);
  return 0;
}

Build it: speed and distance with the right types

This is step 1 of the module project, a bike computer. A magnet on the wheel passes a sensor once per turn. From the time between pulses and the wheel's size, the computer shows speed and distance. Pick a type too small and the odometer jumps back to zero after one long ride.

Lab: Speed and distance without overflow

  • speed_x10(circ_mm, period_ms) returns the speed in tenths of a km/h for a wheel of circumference circ_mm turning once every period_ms. Millimetres per millisecond are metres per second, and 1 m/s is 3.6 km/h, so the result is circ_mm * 36 / period_ms. A period of 0 (no pulse yet) gives 0. The product (75780 for a road wheel) does not fit in 16 bits. Here it works by luck, because C promotes the operands to a 32-bit int first, but on a chip with a 16-bit int (an 8-bit AVR) it overflows: write it portably, with the multiplication in uint32_t.
  • distance_m(revs, circ_mm) returns the distance in whole metres after revs turns: revs * circ_mm / 1000. A bike can do 20 million turns in its life, and 20 million times 2100 mm does not fit in 32 bits: use 64-bit arithmetic for the product.
  • print_speed(v_x10) prints the speed as 23.5 km/h and a newline.

Going deeper

Interview question: How do you choose the width of an energy meter's total counter?

Answer: From the worst case: the largest load times the product's lifetime, in the counter's unit. A 100 kW load for 20 years is about 17.5 GWh, which needs more than 32 bits at Wh resolution, so the total is 64-bit (or counted in larger units with the remainder kept separately). Then check every intermediate calculation's width, store the total with a CRC in non-volatile memory, and test the rollover behaviour explicitly.

Interview question: Why does uint8_t a = 200, b = 100; if (a + b > 255) evaluate as true?

Answer: Integer promotion: before arithmetic, uint8_t operands are promoted to int, so a + b is computed as the int 300, which is greater than 255. The wrap-around to 44 would only happen if the result were stored back into a uint8_t. Knowing where promotion happens explains many surprises with small types, including comparisons and shifts.

Interview question: What happens when you compare a negative int with an unsigned int?

Answer: The usual arithmetic conversions convert the int to unsigned, so -1 becomes a very large value (0xFFFFFFFF on 32-bit) and -1 < 1u is false. Compilers warn about signed-unsigned comparisons with -Wall -Wextra. Keep comparisons within one signedness, or cast deliberately after checking the signed value is non-negative.

Explain it: In your own words, explain why firmware uses uint32_t instead of int or long.

Answer: The C standard only gives minimum sizes for int and long, so they differ between compilers and targets: int is 16 bits on many 8-bit microcontrollers and 32 bits on Arm, and long is 32 or 64 bits. Registers, protocol fields and file formats have exact sizes, so firmware uses the fixed-width types from stdint.h, such as uint32_t and int16_t, which have exactly that many bits on every platform. That makes the code portable and the intent clear.