How do you compare two signed numbers in z80 assembly?
Signed arithmetics - this includes compare - uses the Overflow flag (P/V) to signal any over/underflow. To decode it has to be seen in relation with the sign flag. This is a two step process:
Step 1: Test for equal.
- If Z flag is set then V (value compared) is equal to A
- If Z flag is reset then Vr is not equal to A
Step Two: Test for less or greater
- If S and P/V are the same then V is greater (*) an A
- If S and P/V are different then V is less than A
S and P/V are as well the same if the number is equal to A, so without the first test comparing S an P/V can be used to catch a number greater or equal to A.
On a Z80 (or any 8080 follow up) 1 to 3 flags need to be checked, depending on the question asked the resulting jumps may be rather complex. Now, drawing this up as a table gives additional insight
Z S P/V
0 0 0 V>A
0 0 1 V<A
0 1 0 V<A
0 1 1 V>A
1 0 0 V=A
1 0 1 V=A (doesn't happen anyway)
1 1 0 V=A ( " " " )
1 1 1 V=A
Looking at the first 4 lines looks quite like an XOR operation, doesn't it?
A B Q
0 0 0
0 1 1
1 0 1
1 1 0
If we just had a way to XOR flag bits ... to bad that moving them to A not only destroys A, but also requires a lot of code. But help is near, there is an a variation of CP that copies the sign into an accumulator bit: SUB :))
Lets try this:
JP Z,Equal -> V was equal to what A was
JP PO,No_XOR -> P/V not set, so XOR wouldn't do anything useful
XOR 80h -> S := S XOR P/V - as tabled above
JP M,Less -> V was less than what A was
JP PE,Greater -> V was greater than what A was
Nifty, isn't it :)) No just remove the unneeded jumps. Ofc, if you need to preserve A, then the usual jumps are back on track.
In general carry is not meant for comparison, it's sole purpose is to handle carry (borrow) on multi byte/word operations. Now, in the special case of unsigned numbers, testing it (at the end), instead of operating on S vs. P/V, does simplify code. Bottom line: above citation is valid, but only (and as already assumed) in case of unsigned numbers.
(Hint: Instead of wasting time on more or less special web pages, get a copy of Rodney Zacks's Programming the Z80, eventually the standard book for this purpose - and conveniently (and legal) available as PDF on Gaby's Z80-Info site)