diff --git a/src/convert.asm b/src/convert.asm index 2e069bf..2babc10 100644 --- a/src/convert.asm +++ b/src/convert.asm @@ -1 +1,99 @@ %include "src/constants.asm" + +section .bss + cnvtBuff resb 21 +section .text + global int2str + global uint2str + +;----- int2str(num) -----; +; Converts a signed integer to a string +; Return value: Pointer to string containing the converted number +; Used registers: +; rax* num stored for div >> (ret) pointer to cnvtBuff[] +; rcx* Counts length of created string +; rdx* modulo as calculated by div >> character storage for cnvtBuff +; rdi* (arg) number to convert to string >> Remembers if num is negative +; rsi* Points to cnvtBuff for writing characters +; r8* Dividor for div +int2str: + mov rsi, cnvtBuff + test rdi, rdi + jnz .notZero + mov byte [rsi], '0' + mov byte [rsi+1], EOS + jmp .quit + + .notZero: + mov rax, rdi + xor dil, dil + xor rcx, rcx + test rax, rax + jns .convert + neg rax + mov dil, 1 + .convert: + xor rdx, rdx + mov r8, 10 + div r8 + add rdx, '0' + push rdx + inc rcx + test rax, rax + jnz .convert + test dil, dil + jz .makeString + push byte '-' + inc rcx + .makeString: + pop rdx + mov byte [rsi], dl + inc rsi + loop .makeString + mov byte [rsi], EOS + + .quit: + mov rax, cnvtBuff + ret + +;----- uint2str(num) -----; +; Converts an unsigned integer to a string +; Return value: Pointer to string containing the converted number +; Used registers: +; rax* num stored for div >> (ret) pointer to cnvtBuff[] +; rcx* Counts length of created string +; rdx* modulo as calculated by div >> character storage for cnvtBuff +; rdi* (arg) number to convert to string +; rsi* Points to cnvtBuff for writing characters +; r8* Dividor for div +uint2str: + mov rsi, cnvtBuff + test rdi, rdi + jnz .notZero + mov byte [rsi], '0' + mov byte [rsi+1], EOS + jmp .quit + + .notZero: + mov rax, rdi + xor dil, dil + xor rcx, rcx + .convert: + xor rdx, rdx + mov r8, 10 + div r8 + add rdx, '0' + push rdx + inc rcx + test rax, rax + jnz .convert + .makeString: + pop rdx + mov byte [rsi], dl + inc rsi + loop .makeString + mov byte [rsi], EOS + + .quit: + mov rax, cnvtBuff + ret diff --git a/src/tests.asm b/src/tests.asm index fac9e52..b7b23e2 100644 --- a/src/tests.asm +++ b/src/tests.asm @@ -12,15 +12,18 @@ extern strcpy extern strcat extern strclr ; convert.asm +extern int2str +extern uint2str section .rodata - TEST_print equ 0 - TEST_puts equ 0 + TEST_print equ 1 + TEST_puts equ 1 + TEST_int2str equ 1 ;includes uint2str TEST_printf equ 1 - TEST_strlen equ 0 - TEST_strcpy equ 0 - TEST_strcat equ 0 - TEST_strclr equ 0 + TEST_strlen equ 1 + TEST_strcpy equ 1 + TEST_strcat equ 1 + TEST_strclr equ 1 str1 db "Hello, world!",EOS str2 db "Hello, World!",EOS @@ -105,6 +108,17 @@ _start: call puts %endif +;--- +;--- int2str() / uint2str() +;--- +%if TEST_int2str + ; x/s $rax after calls to confirm proper output + mov rdi, -569384 + call int2str + mov rdi, -569384 + call uint2str +%endif + ;--- ;--- printf() ;---