Printing floats with printf in x86 nasm 32-bit
As Michael pointed, %f
in printf
expects a double
, so your number must be converted into a double
just before pushing it on the stack for printf
:
global main
extern printf, scanf
section .data
scan_format: db "%f",0
print_format: db "Result: %f",0xA,0
section .bss
result_num: resb 4
section .text
main:
push result_num
push scan_format
call scanf
add esp, 8
sub esp,8 ;reserve stack for a double in stack
mov ebx,result_num
fld dword [ebx] ;load float
fstp qword [esp] ;store double (8087 does the conversion internally)
push print_format
call printf
add esp, 12
ret
push qword [result_num_dub] ;ASSEMBLER ERROR HERE
You cannot do 64 bit operations, like pushing 64 bits at a time, in 32 bit mode. This is why I used the sub esp
method to reserve stack space. Your second program just needs this:
section .text
main:
push result_num
push scan_format
call scanf
add esp, 8
fld dword [result_num]
fstp qword [result_num_dub]
push dword [result_num_dub+4] ;pushes 32 bits (MSB)
push dword [result_num_dub] ;pushes 32 bits (LSB)
push print_format
call printf
add esp, 12 ;<-- 12 bytes, not 8.
ret