Binary arithmetic and signed integers
Doing maths in binary
- A computer adds, subtracts and stores negative numbers — all in binary.
- The clever trick is two's complement, which turns subtraction into addition.
- Let's build it up from simple binary addition.
Binary addition
- Add column by column from the right, carrying a 1 just like in denary.
- The rules: $0+0=0$, $0+1=1$, $1+1=10$ (write 0, carry 1), $1+1+1=11$ (write 1, carry 1).
- Worked:
0101$+$0011$=$1000(i.e. $5 + 3 = 8$). - Overflow happens when the result needs more bits than the register holds — the carry out of the leftmost column is lost.
Add the binary numbers 0101 + 0011. Give the 4-bit result.
$5 + 3 = 8$, which is 1000 in binary.
Overflow in binary addition means:
Overflow occurs when the sum is too large to fit in the available bits; the carry out of the leftmost column is lost.
Subtraction by two's complement
- To do $A - B$: form the two's complement of $B$ (invert every bit, then add 1), then add it to $A$, and discard any final carry-out.
- Worked, 4-bit: $7 - 3$. Two's complement of
0011→ invert1100→ add 1 →1101. 0111$+$1101$=$1 0100→ discard the leading 1 →0100$= 4$. ✓
What is the 4-bit two's complement of 0011? (invert, then add 1)
Invert 0011 → 1100, then add 1 → 1101 (which represents $-3$).
Two's complement signed integers
- The most significant bit (MSB) is the sign bit: 0 = positive, 1 = negative.
- To read a negative number: invert all bits, add 1, then put a minus sign on the result.
- e.g.
11111101→ invert00000010→ add 1 →00000011$= 3$, so the value is $-3$. - For $n$ bits the range is $-2^{n-1}$ to $+2^{n-1}-1$; for 8 bits, $-128$ to $+127$.
Read the 8-bit two's complement number 11111101 as a signed denary value.
MSB is 1 (negative). Invert → 00000010, add 1 → 00000011 $= 3$, so the value is $-3$.
What is the largest positive value an 8-bit two's complement number can hold?
Range is $-2^{7}$ to $2^{7}-1$, i.e. $-128$ to $+127$. The maximum is 01111111 = 127.
Binary Coded Decimal (BCD)
- In BCD, each denary digit is stored as its own 4-bit pattern (0000–1001 only).
- $93$ in BCD is
1001 0011— not the same as binary 93 (0101 1101). - Used in calculators, digital clocks and 7-segment displays, and for currency (it avoids the rounding errors of storing $0.1$ in pure binary).
Write the denary digit $9$ as a 4-bit BCD pattern.
$9$ is 1001. In BCD each denary digit gets its own nibble (0000–1001).
You've got it
- add binary column by column with carries; overflow = result too big for the register
- subtract by adding the two's complement (invert + add 1), then discard the carry
- signed: MSB is the sign bit; 8-bit range $-128$ to $+127$
- BCD stores each denary digit as its own nibble (0000–1001)