Cap8 - Carry and Overflow - (Z80 Assembly Lang Prog For Studs, Hutty R.)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

8 Carry and overflow

Carry and overflow are two conditions which can occur during
addition and subtraction. The conditions affect bits in the flag
register which can then be tested by conditional jump
instructions.

8.1 CARRY

Carry normally refers to the carry out of the most significant


bit during the addition of two numbers. For example, the sum

00110011 (+51)
+ 00011100 (+28)

01001111

does not produce a carry, but the sum

11111110 (-2)
+ 11111111 (-1)

[1] 11111101 (-3)

has produced a carry which would be ignored as far as the result


of the 8-bit addition is concerned.

Exercise 8.1
Does 11000000 + 01000000 produce a carry?

8.2 THE CARRY FLAG

When an ADD instruction is executed the CARRY FLAG will be set to


1 if carry occurs, otherwise it will be reset to O. The carry
flag can then be tested by using one of the conditional jump
instructions

JP C,label
JP NC,label
JR C,label
or JR NC,label

where C stands for Carry (the carry flag is set to ,1) and NC
stands for No Carry (the carry flag is reset to 0).

38
R. Hutty, Z80 Assembly Language Programming for Students
© Roger Hutty 1981
The carry flag is also used to indicate that a SUB instruction
needed to borrow a 1 during subtraction of the two most
significant bits.

Exercise 8.2
Will the instruction labelled NCARRY or CARRY be executed after
the JP instruction in the following sequence?

LD A,7
SUB 8
JP NC,NCARRY
CARRY:

The carry flag is involved in the execution of shift, rotate and


decimal adjust instructions, which are dealt with later in the
book.

There are two instructions which may be used to change the value
of the carry flag. The instructions are SCF which Sets the Carry
Flag to 1, and CCF which Complements the Carry Flag. These two
instructions are specified in Table C.6 in Appendix C.

Exercise 8.3
Write a sequence of instructions which resets the carry flag to O.

8.3 OVERFLOW

Overflow occurs when the result of an operati'on is outside an


arithmetic range. For 8-bit registers and bytes the range is
-128 to +127.
For addition, two numbers with different signs will never cause
overflow. However, when adding two positive numbers or two
negative numbers overflow mayor may not occur. For example, the
sum

01100100 (+100)
+ 00110001 (+49)

10010101 (-107)

does not produce the correct arithmetic result because the real
sum of the two numbers, +149, is greater than +127 and is
therefore outside the arithmetic range.

For subtraction, overflow can only occur if the two numbers have
different signs. For example, the subtraction

01111110 (+126)
- 11000000 (-64)

[1] 10111110 (-66)

39

You might also like