Skip to content

Instantly share code, notes, and snippets.

@cr1901
Last active December 10, 2018 09:46
Show Gist options
  • Save cr1901/7c5cc6739dee36b82f1183ed57748401 to your computer and use it in GitHub Desktop.
Save cr1901/7c5cc6739dee36b82f1183ed57748401 to your computer and use it in GitHub Desktop.
Signed Subtraction Flags Cheat Sheet

Flags table for the operation: a - b

Flag Legend

  • Z- Is the result zero?
  • S- Is the top bit of the result set?
  • C- Did a borrow not occur (see Subtraction on the 6502)?
    • For architectures with a true borrow flag, invert the C bit.
  • V- Does the result of a - b fit within signed 16-bit range?

Other notes

  • a and b are treated as 16-bit signed numbers.
  • -x is unary negation.
  • Entries in columns Z, S, C, and V are boolean expressions that evaluate to the value of each flag.

Flags Table

Condition Z S C V
a > 0, b > 0, a >= b a == b 0 1 0
a > 0, b > 0, a < b 0 1 0 0
a > 0, b < 0 (a > b) 0 a + -b > 32767 0 a + -b > 32767
a < 0, b > 0 (a < b) 0 a - b >= -32768 1 a - b < -32768
a < 0, b < 0, a >= b a == b 0 1 0
a < 0, b < 0, a < b 0 1 0 0

Conclusions

  • If a >= b, then S and V will have the same value (S xnor V, or S == V).
  • If a < b, then S and V will have opposite values (S xor V).
  • By using only the first table entry, you can derive flags for unsigned compares too!
    • If a >= b, then C == 1.
    • If a < b, then C == 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment