w1coding.comAll tutorials

Assembly Floating

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

Floating Point Arithmetic

Floating point operations in assembly are typically performed using the Floating Point Unit (FPU) or SIMD instructions like SSE (Streaming SIMD Extensions).

FPU Instructions

  • fld: Load a floating-point value onto the FPU stack.
  • fadd: Add two floating-point values.
  • fsub: Subtract two floating-point values.
  • fmul: Multiply two floating-point values.
  • fdiv: Divide two floating-point values.
  • fstp: Store and pop a floating-point value from the FPU stack.

Example: Simple Floating Point Calculation

This example demonstrates loading two floating-point values and performing arithmetic operations.

section .data
    num1 dq 5.5         ; First floating-point number
    num2 dq 2.2         ; Second floating-point number
    result dq 0.0       ; To store the result

section .text
    global _start

_start:
    fld qword [num1]    ; Load num1 onto the FPU stack
    fadd qword [num2]   ; Add num2 to the value on the FPU stack
    fstp qword [result] ; Store the result and pop the FPU stack

    mov rax, 60         ; System call: exit
    xor rdi, rdi        ; Exit code: 0
    syscall
    

Example: Using SIMD for Floating Point Arithmetic

SIMD instructions operate on multiple data points simultaneously.

section .data
    num1 dq 5.5, 6.5    ; Two floating-point numbers
    num2 dq 2.2, 3.2    ; Two more floating-point numbers
    result dq 0.0, 0.0  ; To store results

section .text
    global _start

_start:
    movaps xmm0, [num1] ; Load num1 into xmm0
    movaps xmm1, [num2] ; Load num2 into xmm1
    addps xmm0, xmm1    ; Perform parallel addition
    movaps [result], xmm0 ; Store the results

    mov rax, 60         ; System call: exit
    xor rdi, rdi        ; Exit code: 0
    syscall
    

Key Notes

  • FPU operations use a stack-based model; plan your stack operations carefully.
  • SIMD operations are faster for large datasets and are preferred in modern applications.
  • Ensure proper alignment when working with SIMD registers to avoid runtime errors.