如何在 NASM 中将两个数字(整数和浮点数)相加?

Oma*_*cia 2 x86 assembly gcc nasm x87

我有这段代码,应该添加两个数字,一个浮点数(3.25)和一个整数(2)。

编辑:

extern _printf, _scanf
global _main
section .bss
  num1: resb 4
section .data
  format_num: db "%f", 10, 0
section .text
_main:

  mov dword [num1], __float32__(3.25)
  add num1,  2

  sub esp, 8
  fld dword [num1]
  mov dword [num1], eax
  fstp qword [esp]
  push format_num
  call _printf
  add esp, 12

ret
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

test.asm:11:错误:操作码和操作数的组合无效

我期望的输出是:

5.250000

Mic*_*tch 6

关于 x87 FPU 的优秀教程超出了 Stackoverflow 的范围,但我可以推荐MASM 论坛上的教程。另一个好的来源是英特尔指令集参考。特别是,大多数以 开头的函数F都是 x87 浮点单元 (FPU) 相关指令。

一般来说,您不能只将浮点值与整数相加。它们是两种不同的表示。您可以做的是将整数转换为浮点值,然后用它进行浮点计算。特别是,以 开头的指令FI是浮点运算,涉及将整数存储器操作数转换为浮点。

给猫剥皮的方法有很多种,但如果您查看上面链接的 FPU 教程,您可能会意识到一种简单的方法是这样做:

sub esp, 8           ; Allocate space on stack to store integer
mov dword [esp], 2   ; Move the 32-bit integer value onto stack temporarily
fild dword [esp]     ; Load integer 2 from stack into top of FPU stack at st(0)
                     ;    Converting it to 2.0 in the process
mov dword [esp], __float32__(3.25)
                     ; Move 3.25 onto stack temporarily
fadd dword [esp]     ; Add 3.25 to st(0). Result in st(0). So st(0)=5.25
fstp qword [esp]     ; Store 64-bit double to stack for printf and pop FPU stack.
Run Code Online (Sandbox Code Playgroud)

我没有使用全局变量在主内存中临时存储值,而是使用我们保留的堆栈空间作为临时暂存区域来加载/操作 x87 FPU。

如果您使用的 CPU 支持 SSE2 指令集(这包括任何 32 位模式的 X86-64 处理器),那么您还有其他选择。一种是使用SIMD指令和寄存器进行32位和64位浮点运算。使用指令集参考,您会发现一些有用的指令,例如:

  • cvtsi2sd:将 Dword 整数转换为标量双精度 FP 值
  • cvtss2sd:将标量单精度 FP 值转换为标量双精度 FP 值
  • addsd :添加标量双精度浮点值
  • movsd :移动标量双精度浮点值

标量单精度 FP 值是 32 位浮点数。标量双精度是 64 位双精度。

sub esp, 8
mov dword [esp], 2      ; Load integer 2 (32-bit signed value) onto stack temporarily
cvtsi2sd xmm0, [esp]    ; Convert 2 on stack to 64-bit float and store in XMM0
mov dword [esp], __float32__(3.25)
                        ; Load 32-bit float value of 3.25 onto stack
cvtss2sd xmm1, [esp]    ; Load 32-bit single and convert it to 64-bit double. Store in XMM1
addsd xmm0, xmm1        ; Add 64-bit float in XMM0 and XMM1 store XMM0
movsd qword [esp], xmm0 ; Move 64-bit float back onto stack to be printed by printf
Run Code Online (Sandbox Code Playgroud)