ext mpy16,sdelm
public rten1,radbin
; RTEN1 performs decimal conversion of the string at HL.
rten1: ld de,10 ; Decimal radix base
; Fall through to generalized
; ..radix conversion routine
; This routine converts the string pointed to by HL using the radix
; passed in DE. If the conversion is successful, the value is returned in BC.
; HL points to the character that terminated the number, and A contains that
; character. If an invalid character is encountered, the routine returns with
; the carry flag set, and HL points to the offending character.
radbin: ld bc,0 ; Initialize result
rdx1: or a ; Make sure carry is reset
call sdelm ; Test for delimiter (returns Z if delimiter)
ret z ; Return if delimiter encountered
sub '0' ; See if less than '0'
ret c ; Return with carry set if so
cp 10 ; See if in range '0'..'9'
jr c,rdx2 ; Branch if it is valid
cp 'A'-'0' ; Bad character if < 'A'
ret c ; ..so we return with carry set
sub 7 ; Convert to range 10..15
rdx2:
cp e ; Compare to radix in E
ccf ; Carry should be set; this will clear it
ret c ; If carry now set, we have an error
inc hl ; Point to next character
push bc ; Push the result we are forming onto the stack
ex (sp),hl ; Now HL=result, (sp)=source pointer
call mpy16 ; HLBC = previous$result * radix
ld h,0 ; Discard high 16 bits and
ld l,a ; ..move current digit into HL
add hl,bc ; Form new result
ld c,l ; Move it into BC
ld b,h
pop hl ; Get string pointer back
jr rdx1 ; Loop until delimiter
end