Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding floating point/double numbers in assembly

Tags:

c

x86

assembly

x87

I am trying to experiment with inline assembly, and I am trying to add decimal numbers (no, NOT integers) in inline assembly. Issue is, when I call the following function:

inline double ADD(double num1, double num2) {
  double res;
_asm{

    push eax; push the former state of eax onto stack
    mov eax, num1;
    add eax, num2;
    mov res, eax;
    pop eax; restore the former state of eax now that we are done   
     }  return res;}

The compiler complains of improper operand size at the inline assembly (ALL lines of assembly excluding the push and pop instruction lines). So I have to change to an integer type, such as unsigned long, and then it works, but of course only supports integer types; decimal results are rounded.

Is there any way to add in assembly that allows for decimal results like 8.4?

like image 447
scrat101 Avatar asked Aug 07 '12 19:08

scrat101


People also ask

How do you do a floating point in assembly?

In assembly language, there are at least two standard formats for floating-point numbers: short and long. Short floating-point (32 bits): The first bit is the sign bit: 0 for positive and 1 for negative. The next 7 bits are the exponent: -64 to +63, stored as 0 to 127.

What is the meaning of floating point instruction add add?

The . D means double precision floating point. ADD.D F4,F0,F2. Means add the contents of floating registers F0 and F2 as double precision floating point numbers and store the result into register F4.


2 Answers

I haven't done x87 assembly in a decade, but it should be something like:

fld num1   ; load num1 and push it onto the fpu stack
fld num2   ; load num2 and push it onto the fpu stack
faddp      ; pop two numbers, add them, push sum on the stack
fstp res   ; pop sum from the stack and store it in res
like image 172
fredoverflow Avatar answered Oct 21 '22 05:10

fredoverflow


The instruction you probably want is ADDSD, but I don't know for sure.

Here's the link to Intel's instruction set manuals. http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html/

They used to mail you hard copies for free, but it looks like that's no longer true.

like image 43
Rob K Avatar answered Oct 21 '22 06:10

Rob K