我正在尝试从原始二进制字符串中分配一个浮点数,但我没有得到我期望的结果。
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)
(我知道字节序。)
我试图直接分配浮点数,但我仍然得到一些奇怪的输出(所有 * 的意思是什么?)。
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() 来帮助我)。