Sub topic 11
Status Flags: Zero, Negative, Carry, and Overflow
Assume you know binary numbers, two’s complement representation, registers, and basic ALU operations. A status flag is a one-bit result record produced by the arithmetic logic unit (ALU). The control unit and later instructions can use these bits for conditional branches.
The four common flags
For an operation such as addition or subtraction, processors commonly update these flags:
| Flag | Meaning | Typical test |
|---|---|---|
| Zero (Z) | The fixed-width result is zero | `result == 0` |
| Negative (N) | The result’s most significant bit is 1 | Signed result is negative |
| Carry (C) | An unsigned carry leaves the most significant bit | Unsigned overflow |
| Overflow (V) | A signed result cannot fit in the available bits | Signed overflow |
The negative flag is usually copied from the result’s most significant bit. For an 8-bit result, bit 7 is the sign bit.
Carry and overflow are different
Consider 8-bit addition. The representable unsigned range is 0 through 255. The signed two’s complement range is −128 through 127.
The addition
1111 1111
0000 0001
---------
1 0000 0000produces an 8-bit result of 0000 0000 and a carry-out of 1. Therefore, Z is 1 and C is 1. Interpreted as signed values, −1 + 1 = 0, so V is 0.
Now consider:
0111 1111
0000 0001
---------
1000 0000Both operands are positive, but the result has a sign bit of 1. The signed calculation 127 + 1 cannot fit in 8 bits, so V is 1. There is no carry-out, so C is 0.
For addition, signed overflow occurs when both operands have the same sign but the result has the opposite sign:
V = (sign_a == sign_b) and (sign_result != sign_a)For subtraction, overflow occurs when the operands have different signs and the result’s sign differs from the first operand’s sign.
Computing the flags
def add8(a, b):
"""Return (8-bit result, carry, signed overflow)."""
total = a + b
result = total & 0xFF
carry = (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, overflow
print(add8(0x7F, 0x01)) # (128, 0, 1)
print(add8(0xFF, 0x01)) # (0, 1, 0)The result is masked with 0xFF because the machine keeps only eight result bits. The discarded ninth bit becomes the carry flag.
Exercise
For 8-bit two’s complement addition, what are the carry and overflow flags for 0x80 + 0x80?
Show answer
The result is 0x00 with a carry-out of 1. Carry is 1. Since −128 + −128 is outside the signed range, overflow is also 1.