kvisc/ka/crt/fmt/ltostr.k

88 lines
1.2 KiB
Plaintext

; The OS/K Team licenses this file to you under the MIT license.
; See the LICENSE file in the project root for more information.
;
; void itoa(char *buf, int num, int base)
;
itoa:
mov ax3, 1
jmp ltostr
;
; void utoa(char *buf, int num, int base)
;
utoa:
nul ax3
jmp ltostr
;
; void ltostr(char *buf, int num, int base, bool signed)
;
ltostr:
mov eax, ax0
nul ecx
; make sure base is in [2, 32]
bltu ax2, 2, .bad
bltu 36, ax2, .bad
; deal with zero
bzr ax1, .is_zero
; deal with base 10 signedness
bzr ax3, .conv
bne ax2, 10, .conv ; base 10
shr ecx, ax1, 63 ; extract ax1 sign
jrcxz .conv
neg ax1 ; NEG if negative
; main loop
.conv:
bzr ax1, .fini
rem edx, ax1, ax2 ; ax1 % base
blt 9, edx, .nondec ; edx > 9 ?
add edx, '0'
jmp .next
.nondec:
add edx, 55 ; 'A' - 10
.next:
mov b[ax0], edx
inc ax0
div ax1, ax2
jmp .conv
; add minus flag, null-terminate and reverse
.fini:
jrcxz .cxz
mov b[ax0], '-'
inc ax0
.cxz:
nul b[ax0]
call strrev2, eax
ret
;
; exceptional cases
;
.bad:
mov b[ax0], 0
ret
.is_zero:
mov b[ax0], 48 ; '0'
mov b[ax0+1], 0
ret