How to use floating point numbers in x86-64 assembly?

I am struggling with some kind of x86-64 build, and floating point numbers give me a headache. For example, when I run this code:

section .data omega: dq 2.0 omega2: dq 3.0 section .text global func func: push rbp mov rgp, rsp FINIT FLD qword [omega] FLD qword [omega2] FADD st0, st0 mov rsp, rbp pop rbp ret 

This function is called from C code: printf("%Lf \n", func() ); Unfortunately, the result is some bizarre number ... I tried to add two integers using FIADD and it worked fine. I have already dug up a ton of material, but maybe someone here can point me to a decent FPU tutorial or share my experience and wisdom :)

Shutdown:

  • language: assembler x86-64
  • Assembler: nasm v. 2.09.04 installed from repositories
  • compiler (for C): gcc v. 4.5.2 (installed with Ubuntu)
  • OS: Ubuntu 11.04 64 bit on Oracle VM
  • Operating System: Windows 7 SP1 64bit
  • Processor: Intel i5 - 2430M 64 bit (double checked: D)
  • Problem: FPU cannot add two numbers :(

Just in case: in the end I hope to use FSINCOS and other fancy FPU instructions, but seeing that even simple addition fails ...

Thanks to everyone in advance!

+4
source share
2 answers

So, in the end it turned out that my problems were due to the fact that the FPU registers were organized as a stack, and I did not pay enough attention to it, which led to garbage and unwanted residues. Switching from the "standard" to the "pop" versions of the instructions helped!

In any case - thanks to everyone who bothered to read, this is very much appreciated! :)

If anyone is interested, I performed class assignment when I had to calculate the movement of one planet from the point of view of another (geocentric model) in the assembly. The final result, translated into processing, can be viewed here.

+2
source

The L qualifier for printf% f makes this argument a long double (80-bit float), which is not an assembly data type. Remove L and the default will be the double (64-bit float) that you use.

In addition, it should be

  FADD st1, st0 

to add two numbers together. Otherwise, it will double the second value.

0
source

Source: https://habr.com/ru/post/1415875/


All Articles