1
0
mirror of https://gitlab.os-k.eu/os-k-team/kvisc.git synced 2023-08-25 14:05:46 +02:00
kvisc/ka/crt/fmt/itoa.k

101 lines
1.4 KiB
Plaintext
Raw Normal View History

2019-05-30 18:31:50 +02:00
; The OS/K Team licenses this file to you under the MIT license.
; See the LICENSE file in the project root for more information.
;
2019-06-05 22:11:45 +02:00
; char *_itoa(char *buf, int num, int base, int unsi)
2019-05-30 18:31:50 +02:00
;
2019-06-05 22:11:45 +02:00
; Acts as itoa if unsi == 0, as utoa otherwise
;
_itoa:
mov rax, ax0
2019-06-15 20:21:38 +02:00
xor lx0, lx0
2019-06-05 22:11:45 +02:00
; make sure base is in [2, 32]
cmp ax2, 2
2019-06-06 22:07:34 +02:00
jmp.b .bad
2019-06-05 22:11:45 +02:00
cmp ax2, 36
2019-06-06 22:07:34 +02:00
jmp.a .bad
2019-06-05 22:11:45 +02:00
; deal with zero
test ax1, ax1
2019-06-06 22:07:34 +02:00
jmp.z .zero
2019-06-05 22:11:45 +02:00
; deal with base 10 signedness
test ax3, ax3 ; unsigned mode
2019-06-06 22:07:34 +02:00
jmp.nz .conv
2019-06-05 22:11:45 +02:00
cmp ax2, 10 ; base 10
2019-06-06 22:07:34 +02:00
jmp.nz .conv
2019-06-05 22:11:45 +02:00
2019-06-15 20:21:38 +02:00
sgn lx0, ax1 ; extract ax1 sign
2019-06-05 22:11:45 +02:00
2019-06-15 20:21:38 +02:00
cmp lx0, -1 ; negative?
2019-06-13 22:20:35 +02:00
neg.z ax1
2019-06-05 22:11:45 +02:00
; main loop
.conv:
test ax1, ax1
2019-06-06 22:07:34 +02:00
jmp.z .fini
2019-06-05 22:11:45 +02:00
2019-06-15 20:21:38 +02:00
mov lx1, ax1
mod lx1, ax2 ; ax1 % base
2019-06-05 22:11:45 +02:00
2019-06-15 20:21:38 +02:00
cmp lx1, 9 ; lx1 > 9 ?
2019-06-06 22:07:34 +02:00
jmp.a .nondec
2019-06-05 22:11:45 +02:00
2019-06-15 20:21:38 +02:00
add lx1, 48 ; '0'
2019-06-05 22:59:32 +02:00
jmp .next
.nondec:
2019-06-15 20:21:38 +02:00
add lx1, 87 ; 'a' - 10
2019-06-05 22:11:45 +02:00
.next:
2019-06-15 20:21:38 +02:00
mov b[ax0], lx1
2019-06-05 22:11:45 +02:00
inc ax0
div ax1, ax2
jmp .conv
2019-06-05 22:59:32 +02:00
; add minus flag, null-terminate and reverse
2019-06-05 22:11:45 +02:00
.fini:
2019-06-15 20:21:38 +02:00
cmp lx0, -1
2019-06-06 22:07:34 +02:00
mov.z b[ax0], 45 ; '-'
inc.z ax0
2019-06-05 22:59:32 +02:00
2019-06-05 22:11:45 +02:00
mov b[ax0], 0
2019-06-05 22:59:32 +02:00
mov ax0, rax
call strrev2
2019-06-05 22:11:45 +02:00
ret
;
; exceptional cases
;
.bad:
mov q[errno], EINVAL
2019-06-15 20:21:38 +02:00
mov b[ax0], 0
2019-06-05 22:11:45 +02:00
ret
.zero:
mov b[ax0], 48 ; '0'
mov b[ax0+1], 0
ret
;
; wrappers
;
itoa:
mov ax3, 0
jmp _itoa
utoa:
mov ax3, 1
jmp _itoa