3 Replies - 1153 Views - Last Post: 26 May 2018 - 01:57 AM

#1 Scruberito   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 24-May 18

Printing floating number - NASM

Posted 24 May 2018 - 02:52 PM

Hello! I am trying to create a decimal calculator in assembly (NASM), and I got as far as printing a float number. My code for printing a float number is this:

extern _printf
section .data
    variable dd 2.1
    sign db '%f', 10, 0

section .text
global _main
_main:
    mov ebp, esp; for correct debugging
    push variable
    push sign
    call _printf
    add esp, 8
    ret


Which gives me 0.00000.

Then I tried to load it to the fpu first, and then try to print it like that:

extern _printf
section .data
    variable dd 2.1
    sign db '%f', 10, 0

section .text
global _main
_main:
    mov ebp, esp; for correct debugging
    fld qword[variable]
    sub esp, 8
    fstp qword[esp]
    push sign
    call _printf
    add esp, 12
    ret


but again I got 0.000. I found several topics with similar problems in StackOverflow, but I couldn't make a sense out of them. If someone can help me understand what I am doing wrong, it would be great.

Thank you!

Is This A Good Question/Topic? 0
  • +

Replies To: Printing floating number - NASM

#2 Programmer2004   User is offline

  • D.I.C Head

Reputation: 18
  • View blog
  • Posts: 96
  • Joined: 25-October 17

Re: Printing floating number - NASM

Posted 25 May 2018 - 07:16 AM

Looks like you gave a pointer the value instead of it in the first code. Try writing push [variable] instead of push variable.
Was This Post Helpful? 0
  • +
  • -

#3 Scruberito   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 24-May 18

Re: Printing floating number - NASM

Posted 25 May 2018 - 05:31 PM

On the first code I changed
push variable
to
push dword[variable]
(I added dword because I need to specify size, and I could not use qword), but I still got a 0.00000.
Was This Post Helpful? 0
  • +
  • -

#4 Scruberito   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 24-May 18

Re: Printing floating number - NASM

Posted 26 May 2018 - 01:57 AM

It seems that i finally found a solution. The correct way of printing a float, is to first load it to the FPU regosters, and then move it back to the stack and print it. Like I did in the first code, but a little different:

extern _printf
section .data
    variable dd 2.1
    sign db '%f', 10, 0

section .text
global _main
_main:
    mov ebp, esp; for correct debugging
    mov eax, variable
    fld dword[eax]
    sub esp, 8
    fstp qword[esp]
    push sign
    call _printf
    add esp, 12
    ret


This code prints 2.100000 now!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1