assembly 汇编浮点数学

iovurdzv  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(111)

我正在制作一个编译器,编译成x86_64汇编,我正在尝试实现浮点数学。然而,我很快就遇到了问题,因为浮点数在汇编中是一个难题,所以我试图用它们来练习,但我没有找到运气。
在这个程序中,我想把两个浮点数加在一起,将它们与另一个浮点数进行比较,如果它们相等,则打印一条消息,但没有打印任何内容。

section .data
    float1: dd 3.14
    float2: dd 5.72
    cmp_float: dd 8.86
    msg: db "Is equal!", 10, 0
    msg_len equ $-msg

section .bss
    result: resd 1

section .text
    global _start

_start:
    fld dword [float1]  ; Load float1 into FPU stack
    fld dword [float2]  ; Load float2 into FPU stack
    faddp               ; Add two top floats of the FPU stack and push back onto the FPU stack

    fcomp dword [cmp_float] ; Compare with the top value of the FPU stack

    fstsw ax            ; Store FPU status word in AX register
    sahf                ; Move AH register to FLAGS register

    je .equal
    jmp .exit
.equal:
    mov rax, 1
    mov rdi, 1
    mov rsi, msg
    mov rdx, msg_len
    syscall
.exit:
    mov rax, 60
    mov rdi, 0
    syscall
6uxekuva

6uxekuva1#

我不知道x87和一切,谢谢你@Jester,而是使用SSE(Streaming SIMD Extensions)或AVX(Advanced Vector Extensions)指令集提供的SIMD(单指令多数据)指令:

section .data
    number1 dd 2.5          ; First floating-point number
    number2 dd 1.3          ; Second floating-point number
    result_add dd 0.0       ; Variable to store the addition result
    result_sub dd 0.0       ; Variable to store the subtraction result
    result_mul dd 0.0       ; Variable to store the multiplication result
    result_div dd 0.0       ; Variable to store the division result

section .text
    global _start

_start:
    ; Addition
    movss xmm0, [number1]       ; Load number1 into xmm0
    movss xmm1, [number2]       ; Load number2 into xmm1
    addss xmm0, xmm1             ; Add xmm1 to xmm0
    movss [result_add], xmm0    ; Store the result

    ; Subtraction
    movss xmm0, [number1]       ; Load number1 into xmm0
    movss xmm1, [number2]       ; Load number2 into xmm1
    subss xmm0, xmm1             ; Subtract xmm1 from xmm0
    movss [result_sub], xmm0    ; Store the result

    ; Multiplication
    movss xmm0, [number1]       ; Load number1 into xmm0
    movss xmm1, [number2]       ; Load number2 into xmm1
    mulss xmm0, xmm1             ; Multiply xmm0 by xmm1
    movss [result_mul], xmm0    ; Store the result

    ; Division
    movss xmm0, [number1]       ; Load number1 into xmm0
    movss xmm1, [number2]       ; Load number2 into xmm1
    divss xmm0, xmm1             ; Divide xmm0 by xmm1
    movss [result_div], xmm0    ; Store the result

    ; ... Rest of your code

    ; Exit the program
    mov rax, 60
    mov rdi, 0
    syscall

相关问题