Z80 extend 8-bit to 16-bit
Sometimes you may need to turn an 8-bit value into a 16-bit one. Thankfully this is pretty trivial. For unsigned extension (i.e. upper byte is always 0) just take the naive approach:
ld l, a ; Store low byte
ld h, 0 ; High byte always 0
Sign extension is trickier but still simple. Low byte is copied as-is.
Then we push the sign bit into the carry bit, and exploit the
sbc
instruction to get a 0 or -1 out of it (what we're
doing is A - A - carry, which is the same as getting -carry). Then we
can store that in the upper byte.
ld l, a ; Store low byte
add a, a ; Push sign into carry
sbc a ; Turn it into 0 or -1
ld h, a ; Store high byte