[\<- Signed numbers and subtraction](10.md) # Overflow, Comparison, ALU ## Overflow - Remember, signed numbers, and hardware computation units, have a fixed number of bits - What happens if the result of the addition/subtraction needs more than the available bits? - Need to detect this condition. What happens next depends on the "system" in which the circuit is implemented ### Determining Overflow - Adding two numbers with the same "sign" should not yield a result with the opposite sign ![diagram](11.1.png) ### HW detection of overflow - As humans, we can look at the sum of two numbers and see whether there's overflow - A HW circuit, like a 4-bit adder, needs a way to "flag" whether the result is valid - The carry-in to the sign bit position (C3) should match the carry-out (C4) - Overflow = C3 ^ C4 (for a 4-bit adder) - C7 ^ C8 for an 8-bit adder - Remember: `^` is XOR - Note: adding a negative and positive number can never overflow ### 8-bit signed addition example - Computation of 0xDA + 0xAB - Two negative 8-bit numbers ![diagram](11.2.png) - No overflow: C7 == C8 - Even though C3 != C4 - It's the sign bit that we care about! --- ## Comparison ### Comparators - Often it's usefule to detect comparisons - `==`, `>`, `<`, `!=`, `>=`, `<=` - "Answer" is true/false, yes/no, 1/0 - XOR gates provide an easy means to determine if two bits are equal (`==`) - Apply to each bit position and OR the results - A 1 means the bits don't match => inequality - For unsigned `>` or `<`, start at the MSB (most significatn bit) and find the first mismatch - Really only practical for small # of bits ### Signed Comparison - Subtract the numbers (A-B) and check the result - Three mutually exclusive possibilities - A-B > 0 => A>B - A-B = 0 => A=B - A-B < 0 => A