在我的大学项目中,我必须在 x86 汇编中使用 float 的二进制表示形式进行算术运算。使用 FPU 是被禁止的,所以我尝试读取 float 并将其作为 DWORD 返回,但无论我尝试做什么,我都会得到“-nan”。有什么建议吗?
编辑: 我使用 gcc,它是 32 位代码
C 声明(我无法更改)
extern "C" float func(float num);
*.asm 文件
section .text
global func
func:
;prolog
push ebp
mov ebp, esp
; zapamiętanie rejestrów zachowywanych
push ebx
push esi
push edi
mov eax, DWORD [ebp+8]
;mov eax, 0xffffffff i checked that but i still get the same result
; odtworzenie rejestrów, które były zapamiętane
pop edi
pop esi
pop ebx
;epilog
pop ebp
ret
结果示例(256)
01000011100000000000000000000000
11111111110000000000000000000000
num1: 256.000000
num2: -nan
编辑:
不检查位部分的C代码
#include <stdio.h>
extern "C" float func(float num);
int main()
{
float num1;
float num2;
scanf("%f", &num1);
num2=func(num1);
printf("num1: %f\nnum2: %f\n", num1, num2);
return 0;
}
最佳答案
如果将返回类型 func 声明为 float
,结果将在 FPU (ST0) 中返回。要返回 EAX 中的值,您必须将其声明为整数类型。对于 printf
你必须伪造一个 float 。示例:
来电者.c:
#include <stdio.h>
#include <stdint.h>
extern float asmfunc1(float);
extern uint32_t asmfunc2(float);
int main (void)
{
printf ("asmfunc1: %f\n", asmfunc1(456.78));
uint32_t ifl = asmfunc2(123.45);
float* pfl = (float*) &ifl; // Faking a float
printf ("asmfunc2: %f\n", *pfl);
return 0;
}
被调用者.asm:
section .text
global asmfunc1, asmfunc2
asmfunc1:
fld dword [esp+4]
ret
asmfunc2:
push ebp
mov ebp, esp
mov eax, [ebp+8]
leave
ret
构建并运行:
nasm -felf callee.asm
gcc -m32 callee.o caller.c
./a.out
关于NASM x86 程序集中的 C float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30650303/