z80retro-computinguser-manual

Trouble understanding the Z80 book and flags


I reading the official Zilog User's Manual and I'm having trouble understanding the flags section for each instruction.

In the book it says:

Condition Bits Affected:
    ...
    H: Set if carry from bit 3; reset otherwise
    ...
    C: Set if carry from bit 7; reset otherwise
    ...

What does it mean to set the flag "if carry from bit n". Also another sentence that occurs quite frequently is "Set if borrow from bit n". What do these thing mean ?

Thanks!


Solution

  • Essentially the carry (C) flag tells you if the result of an addition was too big to fit in the accumulator. Or, similarly, if the result of a subtraction was too small to fit in the accumulator. I'll get back to the half-carry (H) flag in a moment.

    Suppose the accumulator (register A) has 37 in it. Then the instruction ADD A,20 is executed. This will put 37+20 = 57 into A. Since A can store values from 0 to 255 the result fits and there is no carry. The carry flag will be 0 (often said as "the carry is clear).

    But if A has 250 in it and an ADD A,20 happens then you end up with 14 in A and the carry flag is 1 (equivalently, it is "set"). What the processor is saying is that 270 didn't fit so it sets the carry flag to indicate the result was bigger than 255 and puts the remainder (270 - 256) into the A register.

    Logically you can view it as saying that after an ADD A the result is 256 * carry plus the A register.

    When doing a subtraction the carry will be set if the result is less than 0. In essence after a SUB A the result is -256 * carry plus the A register.

    The half carry is the same as the carry but it tells you what happens with the lower 4 bits of the A register and what was added to it. By lower 4 bits I mean you take the remainder after dividing by 16.

    Let's go back to adding 37 + 20. 16 goes into 37 two times with a remainder of 5. It only goes once into 20 with a remainder of 4. Now add 4 and 5 together to get 9. Since this is less than 16 it will fit in 4 bits and the half carry will be 0 (or clear).

    But suppose the remainders were 10 and 10. Then we would have 20 which is bigger than 16 so the half carry would be 1 (or set).

    You should keep in mind that the half carry isn't very important or useful. It is only there to support the DAA instruction and even then you don't need to know how it works to use DAA.

    The manual uses the descriptions it does because they clearly and accurately point out how the flags are affected if you are familiar with binary arithmetic. They are also an almost literal description of what the hardware does. For those not familiar with such things (and who is at first?) the description is pretty opaque.

    I encourage you to dig deeper into this and learn binary arithmetic. The wonders of two's complement notation for negative numbers and the interactions between arithmetic and logical operations are quite marvelous.