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.
Theory in plain words
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
| A | B | Carry in | Sum | Carry out |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 | 1 |
Signed vs unsigned (8 bit)
| Bits | Unsigned | Signed (two's complement) |
|---|---|---|
| 0000 0000 | 0 | 0 |
| 0111 1111 | 127 | 127 |
| 1000 0000 | 128 | -128 |
| 1111 1111 | 255 | -1 |
The top bit is the sign bit. An 8 bit signed number covers -128 to 127.
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.
Use the hex view in a debugger to spot byte order problems.
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?
That gives the negative of the same width.
2. What is uint8_t 255 + 1 in C?
Unsigned arithmetic wraps around.
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.