Author Topic: Add integer + floating point numbers  (Read 69 times)

Offline Ferran

  • Jr. Member
  • *
  • Posts: 22
  • Country: ad
Add integer + floating point numbers
« on: September 11, 2020, 04:44:21 PM »
I had worry triying how to solve an important issue and finally i did.

In assembly code nothing is obvious, you can't add easly an integer with a floating pointed number as if, or signed and unsigned ones. All its needed to explicit it in the code.

My intention was to do this (in C language)...

Code: [Select]
#include <stdio.h>

/* ---- data section ---- */

    int i = 100;            // We choose an integer to test
    double d = -87.66;      // really we'll a substraction
    double l;
    double res = 0;

/* .... text section ---- */

void main() {

l = i;                      // Convert INT i to DOUBLE l
res = l + d;                // 'add' l +d and move it to res

/* ---- display res ---- */

    printf("Result is:  %g\n", res);    // res = 12.34
}

... but in assembly code. Today i resolved this issue fine and i want to share with you:

Code: [Select]
;-------------------------------------------------------
; itof.asm
;  Conversion INT to DOUBLE number & diplay it
; ------------------------------------------------------
; Assembly with GNU/Linux x80_86) & NASM compiler & GCC
; ------------------------------------------------------
; 1) Compile:  nasm -f elf64 itof.asm
; 2) Link: gcc -no-pie itof.o -o itof
; 3) Run:./itof
; ------------------------------------------------------

bits 64

extern printf

section .data
    i: dq 100                        ; we'll test an int to add to a double
    d: dq -87.66                     ; really we'll rest d minus d
    l: dq 0.0                        ; l will become in the double value of i
    fmt: db "Result is: %g", 10, 0

section .bss
    res: resq   1                    ; 64 bits for res

section .text
global main

main:
push rbp
   
.addition:                           ; int i --> float l ; res=l+d;
        fild        dword [i]      ; conversion from an INT to DOUBLE \o/
fst     qword [l]        ; store the floating point (no pop)
fadd     qword [d]        ; floating add l (to st0)
fstp     qword [res]      ; store into res (pop flt pt stack)

.display:

        mov rdi, fmt             ; address of format string
movq xmm0, qword [res]       ; res score
mov rax, 1               ; 1 argument to print
        call    printf               ; calling printf
 
pop rbp
       
.exit:  mov rax, 0
ret

NOTE: if you wants to do a substraccion, a multiplication or a division you need to change "fadd" by "fsub", "fmul" or "fdiv"

Enjoy it.
« Last Edit: September 11, 2020, 04:47:24 PM by Ferran »