Home / Learn Chip Programming / Binary Arithmetic, Signed Numbers and Overflow

Binary Arithmetic, Signed Numbers and Overflow

How a chip adds, subtracts and stores negative numbers, and why 255 + 1 can become 0.

In shortBinary addition works like decimal with carry. Negative numbers use two's complement. Fixed width numbers wrap around when they overflow.

Theory in plain words

Two's complement of 5 (8 bit)5 = 0000 0101invert = 1111 1010add 1 = 1111 1011-5 = 0xFB
Two's complement of 5 (8 bit)

What it is

Binary arithmetic is adding, subtracting, multiplying and comparing numbers made of bits. Signed numbers use the two's complement trick to represent negatives.

Why we use it

Hardware has only a fixed number of bits (8, 16, 32). Results can exceed the range and wrap around. Not knowing this causes serious bugs, from wrong sensor readings to security holes.

How it works

Add bit by bit from the right with a carry. To get -x, invert all bits of x and add 1. Subtraction a - b becomes a + (-b), so the CPU needs only an adder.

Where it is used

  • ALU in every CPU
  • Sensor maths on microcontrollers
  • Checksums, counters and timers that wrap around

Binary addition

ABCarry inSumCarry out
00000
01010
11001
11111

Signed vs unsigned (8 bit)

BitsUnsignedSigned (two's complement)
0000 000000
0111 1111127127
1000 0000128-128
1111 1111255-1

The top bit is the sign bit. An 8 bit signed number covers -128 to 127.

8 bit adder with flagsTry it Yourself

Try 200 + 100: the result wraps to 44 and the carry flag becomes 1. Try 100 + 100: as signed numbers this overflows to -56.

Endianness: byte order in memory

A 32 bit value 0x12345678 needs 4 bytes. Little endian chips (x86, most ARM) store the lowest byte first: 78 56 34 12. Big endian stores 12 34 56 78 (network order). Mixing them up garbles data sent between chips.

See little endian bytesTry it Yourself

Use the hex view in a debugger to spot byte order problems.

Careful:In C, signed overflow is undefined behaviour and unsigned overflow wraps. A uint8_t counter that reaches 255 and increments becomes 0. Always choose the type for the range you need.

Quick quiz

1. How do you negate a number in two's complement?

2. What is uint8_t 255 + 1 in C?

Common questions

How do you negate a number in two's complement?

Invert all bits and add 1. That gives the negative of the same width.

What is uint8_t 255 + 1 in C?

0. Unsigned arithmetic wraps around.