I am writing a game for the ZX Spectrum using Z80 and have a bit of a problem. I have manipulated a routine to convert a number held in the A register to a hex value held in DE. I’m not sure of how to convert the other way, ie pass in a hex value in DE and convert this to decimal held in A.
NB: The following routine converts the input to the ascii values that represent the values 0 through to F. EG if a = 255 then d =70 and e = 70 as “F” is ascii value 70.
NumToHex ld c, a ; a = number to convert
call Num1
ld d, a
ld a, c
call Num2
ld e, a
ret ; return with hex number in de
Num1 rra
rra
rra
rra
Num2 or $F0
daa
add a, $A0
adc a, $40 ; Ascii hex at this point (0 to F)
ret
Can anyone advise on a solution to work this in reverse or offer a better solution?
This code takes DE has a hexadecimal number in ASCII and converts it to binary in A. It assumes that DE is a valid hexadecimal number and uses uppercase 'A' through 'F'. It will fail if lowercase letters are used or any ASCII character outside of '0' .. '9' and 'A' .. 'F'.
HexToNum ld a,d
call Hex1
add a,a
add a,a
add a,a
add a,a
ld d,a
ld a,e
call Hex1
or d
ret
Hex1 sub a,'0'
cp 10
ret c
sub a,'A'-'0'-10
ret
Update: Have now tested code and fixed bug in handling of 'A' .. 'F' case in Hex1.
Update: Using "add a,a" which is faster than "sla a". Note that if speed is a concern both conversions can be done much more quickly with lookup tables.