-2

I am having difficulties with understanding what's going on in this code:

LD A, -1;
LD B, 130;
ADD A, B;

And what flags are set to 1 after the ADD instruction.

Basically, I don't know, what value is stored inside the register B.

I cannot find any information whether 130 in LD B, 130 means "1000 0010" or "0 1000 0010" (so subsequently we've got to get rid of the MSB/LSB - I don't know which one).

As a result, I am not sure what is the final value stored in A.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
  • 2
    _"I cannot find any information whether 130 in LD B, 130 means "1000 0010" or "0 1000 0010""_ In the machine code it will be represented in the eight bits `10000010`. However, adding leading zeroes doesn't affect the value, so it doesn't really matter. – Michael Aug 27 '15 at 09:29
  • 3
    As far as the final value of `A` is concerned, it's `130 + -1` == `130 - 1` == `129` (or, if you prefer, `(130 + 255) & 255` == `129`. – Michael Aug 27 '15 at 09:31

1 Answers1

4

The Z80 is an 8-bit processor, therefore your 9-bit number 0 1000 0010 has no relevance. The code you posted

LD A, -1;
LD B, 130;
ADD A, B;

is equivalent to

LD A, 0hFF
LD B, 0h82
ADD A, B

and after the addition register A will contain 0h81

The addition will cause the Carry flag to be set, since it generates a "borrow". The Carry is a result of unsigned addition.

It will cause the Overflow flag to be clear, since there is no "internal carry" from bit 6 to bit 7. Both values were negative to start, and A remains negative. The Overflow Flag is set when the signed sum cannot be represented in the register correctly.

The Zero Flag will be clear, since A is non zero.

The Sign Flag will be set, since A is negative according to bit 7.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • I've got one last question. What if I call an instruction like this: `LD A, -300`. What will be stored in `A`? Will it be just `-300 mod 256`? – Mateusz Piotrowski Aug 27 '15 at 18:19
  • 2
    Yes of course. It will be loaded as `0hD4`, I assume truncation rather than `mod`. – Weather Vane Aug 27 '15 at 18:20
  • 2
    If you can get to grips with hexadecimal notation, so you can work as freely as in decimal, so much the better. It will be much easier to understand what's going on than when using decimal. – Weather Vane Aug 27 '15 at 18:23