gpt4 book ai didi

将二进制转换为 float

转载 作者:行者123 更新时间:2023-11-30 15:48:52 24 4
gpt4 key购买 nike

我试图从原始二进制字符串中分配一个 float ,但我没有得到我所期望的结果。

int main()
{
char recBuffer[] = {0x44, 0x42, 0x96, 0x12, 0x34, 0x56, 0x78};
float tempFloat;
int position = 3;

printf( "recBuffer=0x%x%x%x%x\n", recBuffer[3], recBuffer[4], recBuffer[5], recBuffer[6]);
memcpy( &tempFloat, recBuffer + position, 4 );
printf( "tempFloat=%f (0x%x)\n", tempFloat, tempFloat );
return 0;
}

我的输出如下:

recBuffer=0x12345678
tempFloat=*************************************** (0x40000000)

上述过程适用于整数:

int main()
{
char recBuffer[] = {0x44, 0x42, 0x96, 0x12, 0x34, 0x56, 0x78};
int tempFloat;
int position = 3;

printf( "recBuffer=0x%x%x%x%x\n", recBuffer[3], recBuffer[4], recBuffer[5], recBuffer[6]);
memcpy( &tempFloat, recBuffer + position, 4 );
printf( "tempFloat=%d (0x%x)\n", tempFloat, tempFloat );
return 0;
}

输出:

recBuffer=0x12345678
tempFloat=2018915346 (0x78563412)

(我知道字节序。)

我尝试直接分配 float ,但我仍然得到一些奇怪的输出(所有 * 是什么意思?)。

int main()
{
char recBuffer[] = {0x44, 0x42, 0x96, 0x12, 0x34, 0x56, 0x78};
float* tempFloat;
int position = 3;

printf( "recBuffer=0x%x%x%x%x\n", recBuffer[3], recBuffer[4], recBuffer[5], recBuffer[6]);
tempFloat = (float*)(recBuffer + position);
printf( "tempFloat=%f (0x%x)\n", *tempFloat, *tempFloat );
return 0;
}

输出:

recBuffer=0x12345678
tempFloat=*************************************** (0x40000000)

任何二进制序列都应该给我一个输出,如 0x78563412 = 1.73782443614495040019632524267E34。我不确定为什么 0x40000000 = *。应该是2.0E0。我究竟做错了什么?!任何帮助将不胜感激!

(不幸的是,我正在一台旧的 QNX 机器上工作,没有调试器。只有简单的 printf() 来帮助我)。

最佳答案

printf( "tempFloat=%d (0x%x)\n", tempFloat, tempFloat);
^ |
| |
+---------------------+

%x说明符对于整数很有用,但您将 float 值传递给 printf。所以输出不是一个有意义的值。

关于将二进制转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16616692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com