Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use scanf to read a floating point value in nasm x86 64?

I’m trying to simply read a floating point value and print it using assembly x86 64. So, the value for the variable price, which I’m using as the buffer for the c function scanf doesn’t change when I try to print it.

It’ll print the value it was initially set to, so in the case of the code bellow, it prints 0.0, so the scanf function doesn’t properly change the value for price.

To generate the executable, I’m using the command nasm -f elf64 test.asm && gcc -no-pie test.o -o test.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I doing wrong?

section .data
    price   dq  0.0

    fmt db "%.1f", 0

section .text
    global main
    extern printf, scanf

main:
    push rbp
    mov rbp, rsp

    mov rdi, fmt ;scanf first arg, format string
    mov rsi, price ;scanf second argument, this variable is supposed to change
    mov rax, 0
    call scanf
    
    movq xmm0, [precoTinta] ;in float point mode xmm0 holds the value to be printed
    mov rdi, fmt
    mov rax, 1 ;rax has to be set 1 to float point mode
    call printf

    leave
    ret

>Solution :

The %f formatting specifier calls for a float, not a double. Either use %lf for double precision or adjust price to be a single precision float.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading