Sub topic 8
Two's Complement Arithmetic Refresher
Prerequisites and representation
Assume you know binary and hexadecimal notation, bit positions, and basic register operations. A fixed-width register has a fixed number of bits. Two's complement uses those bits to represent both positive and negative integers.
For an \(n\)-bit value, the signed range is:
\[ -2^{n-1} \text{ through } 2^{n-1}-1 \]
An 8-bit two's complement register therefore represents -128 through 127. The most significant bit is the sign bit: 0 indicates a nonnegative value, and 1 indicates a negative value.
| Decimal value | 8-bit representation |
|---|---|
| 5 | `00000101` |
| -5 | `11111011` |
| 127 | `01111111` |
| -128 | `10000000` |
To encode a negative number:
- Write the positive magnitude in binary.
- Invert every bit.
- Add 1.
For example, \(5\) is 00000101. Inverting gives 11111010; adding 1 gives 11111011, which represents -5.
Addition and subtraction
Two's complement addition uses the same binary adder for signed and unsigned values. Add corresponding bits and pass each carry to the next position. Any carry beyond the most significant bit is discarded in a fixed-width register.
Subtraction is performed as addition of the negated operand:
\[ A-B=A+\text{two's complement}(B) \]
For example, with 8 bits:
def add8(a, b):
"""Return the 8-bit result, carry-out, and signed overflow."""
total = a + b
result = total & 0xFF
carry_out = (total >> 8) & 1
sign_a = (a >> 7) & 1
sign_b = (b >> 7) & 1
sign_result = (result >> 7) & 1
overflow = int(sign_a == sign_b and sign_result != sign_a)
return result, carry_out, overflow
print(add8(0x7F, 0x01)) # (128, 0, 1): 127 + 1 is outside the range
print(add8(0xFF, 0x01)) # (0, 1, 0): -1 + 1 is validCarry versus overflow
Carry-out describes unsigned arithmetic. Signed overflow describes whether the mathematical signed result is outside the representable range.
Signed overflow occurs when:
- two positive operands produce a negative result, or
- two negative operands produce a nonnegative result.
Adding operands with different signs cannot cause signed overflow. For subtraction, overflow occurs when the operands have different signs and the result's sign differs from the sign of the first operand.
Exercise
Using 8-bit two's complement, compute 0x80 + 0xFF. State the result, carry-out, and signed overflow.
Show answer
The bit result is 0x7F, carry-out is 1, and signed overflow is 1 because -128 + -1 is -129, outside the 8-bit signed range.