Skip to content

Commit b39015c

Browse files
author
Zeda
committedMay 25, 2021
More efficient, but destructive 16-bit int to string rourines
1 parent a388c76 commit b39015c

File tree

2 files changed

+118
-0
lines changed

2 files changed

+118
-0
lines changed
 

‎conversion/i16toa_destructive.z80

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#ifndef included_itoa_16
2+
#define included_itoa_16
3+
#include conversion/u16toa_destructive.z80
4+
5+
6+
; A related routine can be found at conversion/itoa_16.z80 which preserves
7+
; registers.
8+
9+
;written by Zeda
10+
;Converts a 16-bit signed integer to an ASCII string.
11+
;Note that this version destroys registers.
12+
13+
#ifndef TOK_NEG
14+
#define TOK_NEG '-'
15+
#endif
16+
17+
i16toa:
18+
;Input:
19+
; DE is the number to convert
20+
; HL points to where to write the ASCII string (up to 7 bytes needed).
21+
;Output:
22+
; HL points to the null-terminated ASCII string
23+
; NOTE: This isn't necessarily the same as the input HL.
24+
;Destroys:
25+
; DE, BC, AF
26+
ld a,d
27+
add a,a
28+
jp nc,u16toa
29+
xor a
30+
sub e
31+
ld e,a
32+
sbc a,a
33+
sub d
34+
ld d,a
35+
inc hl ; make space for a negative sign
36+
call u16toa
37+
dec hl
38+
ld (hl),TOK_NEG
39+
ret
40+
#endif

‎conversion/u16toa_destructive.z80

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#ifndef included_u16toa
2+
#define included_u16toa
3+
4+
; A related routine can be found at conversion/utoa_16.z80 which preserves
5+
; registers.
6+
7+
;written by Zeda
8+
;Converts a 16-bit unsigned integer to an ASCII string.
9+
;Note that this version destroys registers.
10+
11+
u16toa:
12+
;Input:
13+
; DE is the number to convert
14+
; HL points to where to write the ASCII string (up to 6 bytes needed).
15+
;Output:
16+
; HL points to the null-terminated ASCII string
17+
; NOTE: This isn't necessarily the same as the input HL.
18+
;Destroys:
19+
; BC, DE, AF
20+
ex de,hl
21+
22+
; First digit
23+
ld bc,-10000
24+
ld a,'0'-1
25+
inc a ;\
26+
add hl,bc ; | Loop
27+
jr c,$-2 ;/
28+
ld (de),a
29+
inc de
30+
31+
; Second digit
32+
ld bc,1000
33+
ld a,'9'+1
34+
dec a ;\
35+
add hl,bc ; | Loop
36+
jr nc,$-2 ;/
37+
ld (de),a
38+
inc de
39+
40+
; Third digit
41+
ld bc,-100
42+
ld a,'0'-1
43+
inc a ;\
44+
add hl,bc ; | Loop
45+
jr c,$-2 ;/
46+
ld (de),a
47+
inc de
48+
49+
; Fourth digit, remainder is fifth digit
50+
ld a,l
51+
ld h,'9'+1
52+
dec h ;\
53+
add a,10 ; | Loop
54+
jr nc,$-3 ;/
55+
ex de,hl
56+
ld (hl),d
57+
inc hl
58+
add a,'0'
59+
ld (hl),a
60+
inc hl
61+
ld (hl),0
62+
63+
;Now strip the leading zeros
64+
ld c,-6
65+
add hl,bc
66+
67+
ld a,'0'
68+
inc hl ;\
69+
cp (hl) ; | Loop
70+
jr z,$-2 ;/
71+
72+
;Make sure that the string is non-empty!
73+
xor a
74+
cp (hl)
75+
ret z
76+
dec hl
77+
ret
78+
#endif

0 commit comments

Comments
 (0)
Please sign in to comment.