assemblyprintfmasmmasm32masm64

MASM x64 Assembly printf float


.data
temp real4 ?
fmtStr byte 'Result is: %d', 10, 0
fmtStr2 byte 'Result is: %f', 10, 0
i real4 ?

.code
printFloat proc
    sub rsp, 20h
    movsd xmm1, [temp]
    lea rcx, fmtStr2 
    call printf
    add rsp, 20h;
    ret
printFloat endp

Result is always 0.0000000. How i can get value real4 like 5.3434


Solution

  • There are some bugs here.

    temp is a real4 but it should be a real8, or it can stay a real4 but then we need to convert it to a double to pass it to printf (varargs functions don't accept floats, they have to be double).

    The floating point argument also has to be copied in the corresponding integer argument, so rdx in this case.

    Also, 20h is the wrong thing to subtract from rsp, it will leave the stack unaligned and printf may not like that (it didn't like that on my system). If you have that here, you may have it in other functions too, and some combinations would accidentally result in a correct alignment anyway but for the wrong reason.

    The code you showed never assigned a non-zero to temp but I assume you did that elsewhere.

    This code worked for me:

    .data
    temp real8 5.4321
    fmtStr2 byte 'Result is: %f', 10, 0
    
    .code
    
    extrn printf : proc
    
    printFloat proc
        sub rsp, 28h
        movsd xmm1, [temp]
        mov rdx, [temp]
        lea rcx, fmtStr2 
        call printf
        add rsp, 28h
        ret
    printFloat endp
    
    end