I'm trying to do an assignment linking c and nasm. The C program sends me a string representing a 32-bit number (e.g. "000...0011"). I need to print its value, as a string (the string "3" for the example above), using C's printf
with %s
.
Note: to make life easier, I'll ignore the case of negative numbers for now.
I'm new to nasm and so I pretty much have no clue what goes wrong where. I tried converting the given string to a number, store it somewhere, and then have it printed, but this simply prints the binary representation.
Here's my code:
.rodata section
format_string: db "%s", 10, 0 ; format string
.bss section
an: resb 12 ; enough to store integer in [-2,147,483,648 (-2^31) : 2,147,483,647 (2^31-1)]
convertor:
push ebp
mov ebp, esp
pushad
mov ecx, dword [ebp+8] ; get function argument (pointer to string)
mov eax, 1 ; initialize eax with 1 - this will serve as a multiplier
mov dword [an], 0 ; initialize an with 0
ecx_To_an:
cmp eax, 0 ; while eax != 0
jz done ; do :
shr dword [ecx], 1 ;
jnc carry_flag_not_set ; if carry isn't set, lsb was 0
add [an], eax ; else - lsb was 1 - an += eax
carry_flag_not_set:
shl eax, 1 ; eax = eax*2
jmp ecx_To_an ; go to the loop
done:
push an ; call printf with 2 arguments -
push format_string ; pointer to str and pointer to format string
call printf
I don't see how it can be possible to print the int value, given that I can't change the %s
argument that is given to printf
.
Help will be much appreciated.