Home / Learn Verilog / Binary Arithmetic: Add, Subtract, Overflow
Binary Arithmetic: Add, Subtract, Overflow
Add bit by bit with carry, and see what happens when a result does not fit.
The short versionAdd bit by bit with carry, and see what happens when a result does not fit.
Theory in plain words
What it is
Binary addition works like decimal addition with only digits 0 and 1: 1 + 1 = 10 (write 0, carry 1). A result that needs more bits than available overflows and loses the top bit.
Why it matters
Hardware registers have a fixed width, so you must know when a result will not fit.
Mechanically speaking
An N-bit adder gives an N-bit sum plus a carry-out. Subtraction is addition of the two's complement. A wider result variable keeps the carry.
Shows up in
- ALU design
- Counters
- Address calculation
Watch overflow happen
8-bit add: 200 + 100Verilog: edit and run
300 needs 9 bits. In 8 bits the value wraps to 300 - 256 = 44.
- Unsigned N-bit range: 0 to 2^N - 1.
- Overflow: result > 2^N - 1; the top bit(s) are lost.
- To keep the carry, store the sum in a register that is one bit wider.
Check yourself
1. 200 + 100 in 8 bits gives...
300 - 256 = 44.
2. To keep the carry you should...
Add one more bit.