DYSTOPIANPIXEL

Signed and unsigned bytes

See how the same bits can represent positive or negative values.

Next Asset Lab concept artwork showing sprite patterns, palette colours and animation frames
Next Asset Lab concept artwork · Begin with Odin Dev.2k and the foundations of Z80 assembly.
TUTORIAL 2 / PART 02

One byte, two possible interpretations

An eight-bit register holds one of 256 binary patterns. The bits themselves do not say whether a number is signed or unsigned. The programmer decides how to interpret them.

If we treat a byte as unsigned, its range is 0 to 255. Thus $FE means 254. If we treat that same byte as signed two’s-complement, its range is −128 to +127. Then $FE means −2. In either interpretation, the physical bits are identical: 11111110.

00000000$0000
00000001$0111
01111111$7F127127
10000000$80128−128
11111110$FE254−2
11111111$FF255−1

Why two’s-complement works

For an eight-bit signed value with the leftmost bit set, the corresponding signed value is its unsigned value minus 256. So $FE is 254 − 256 = −2; $80 is 128 − 256 = −128. You can also find the eight-bit representation of −2 by starting with positive 2 (00000010), inverting the bits (11111101) and adding one (11111110).

This does not mean the CPU stores an extra minus sign somewhere. It stores only the eight bits. Different instructions and different ways of interpreting flags let a programme work with those patterns.

Why it matters to Next Asset Lab

A colour component, palette index or number of sprite patterns is normally treated as non-negative. But a movement amount or offset might need to express left as well as right, or up as well as down. Treating a signed offset as unsigned can turn what you intended as −2 into 254. Later, when our app manipulates coordinates, this distinction will be essential.

Checkpoint: write down why $FF can be described as either 255 or −1 without any bits changing. If that statement is still confusing, revisit this section before using a flag for a decision.