Printing floats with printf in x86 nasm 32-bit

后端 未结 1 925
小蘑菇
小蘑菇 2020-12-22 06:49

I\'m trying to print out some 32-bit floats using NASM flavored x86 assembly. This is a minimum working example of what I\'m trying to do:

global main
extern         


        
相关标签:
1条回答
  • 2020-12-22 07:27

    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
    
    0 讨论(0)
提交回复
热议问题