← r0mheat z80 lessons: all projects

Z80 assembly: Signed numbers and flags

The same bits can mean a positive or negative number. Learn how the flags describe an arithmetic result.

Carry is not signed overflow

A signed 8-bit number uses two’s complement. Its range is −128 to 127. The top bit is 1 for negative values. For example, 80h means −128 and FFh means −1 when read as signed numbers.

A flag is a one-bit record from an instruction. C reports an unsigned carry or borrow. P/V reports signed overflow after arithmetic. H reports a carry or borrow between bits 3 and 4.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The program first adds 1 to 7Fh. It then adds 1 to 0Fh, and finally subtracts 1 from 0. Watch the flags after each arithmetic instruction.

Registers and flags

Flags

S is the sign bit of the result. Z means the result is zero. H is half-carry. P/V is signed overflow for ADD and SUB. N marks subtraction. C is unsigned carry or borrow. This page ignores undocumented X and Y bits.

Program bytes

Execution trace

#AddressInstructionResultT-states

Read the flags for each example

OperationUnsigned resultSigned resultFlags
7Fh + 01h80h; no carry127 + 1 is too largeP/V=1, C=0
0Fh + 01h10h15 + 1 = 16H=1, P/V=0, C=0
00h − 01hFFh; borrow0 − 1 = −1C=1, P/V=0
8-bit signed−128 to 127
16-bit signed−32,768 to 32,767
8-bit unsigned0 to 255
16-bit unsigned0 to 65,535

The bits do not change when you choose signed or unsigned meaning. Only the way you interpret the value changes.

This lesson uses the standard two’s-complement interpretation. It does not execute signed compare instructions; CP compares bit patterns and sets flags.

Mnemonic glossary

Program mnemonics and directives
NameStands forMeaning here
LDLoadLoads the values used by the examples.
ADDAddAdds a number and updates arithmetic flags.
SUBSubtractSubtracts a number from A.
HALTHaltStops this lesson’s CPU.
ORGOriginAssembler directive. Sets the code address.