Binary arithmetic, two's complement and overflow
A-Level Computer Science · Data Representation: Number Bases, Binary Arithmetic and Character Sets
Adding in binary
Four rules only: $0+0=0$; $0+1=1$; $1+1=10$ (write $0$, carry $1$); $1+1+1=11$ (write $1$, carry $1$). Work right to left exactly as in denary. The carry is the only place mistakes happen, so write it above the column.
Representing negative numbers: two's complement
To make $-n$ in $8$ bits: write $n$ in binary, flip every bit, then add one. So $-45$: $45$ is $00101101$, flipped is $11010010$, plus one is $11010011$. The leftmost bit now acts as a sign: $0$ means positive, $1$ means negative.
Why two's complement and not sign-and-magnitude
Because subtraction becomes addition: $a - b$ is just $a + (-b)$, so the processor needs only an adder. There is also only one representation of zero, whereas sign-and-magnitude has both $+0$ and $-0$.
Overflow
An $8$-bit signed register holds $-128$ to $+127$. If a calculation lands outside that range the result wraps round and is simply wrong — $100 + 50$ gives $-106$. Overflow is detected when adding two numbers of the same sign produces a result of the opposite sign.
Worked example: subtracting with two's complement and detecting overflow
Use an $8$-bit signed register.
(a) Calculate $53 - 45$ by adding the two's complement. (b) Calculate $100 + 50$ and explain the result.
Solution
(a) Step 1: write the two numbers. $53 = 00110101$; $45 = 00101101$.
(a) Step 2: form $-45$. Invert the bits: $11010010$; add one: $11010011$.
(a) Step 3: add. $00110101 + 11010011 = 1\,00001000$. The ninth carry bit is discarded because the register is only $8$ bits, leaving $00001000 = 8$ ✓ exactly $53-45$.
(b) Step 1: add. $100 = 01100100$; $50 = 00110010$. The binary sum is $10010110$.
(b) Step 2: read the result. The sign bit is $1$, so this is a negative number. Its value: invert the bits to get $01101001$, add one to get $01101010 = 106$, so the result is $-106$.
(b) Step 3: explain. Overflow has occurred: two positive numbers were added and the result is negative. The cause is that $150$ exceeds $+127$, the largest value an $8$-bit signed number can represent.