我想從一個原始二進制字符串中分配一個浮點數,但我沒有得到我所期望的。將二進制轉換爲浮點數
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)
(我所知道的Endianness)。
我試着直接分配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()來幫助我)。
我想你的意思是原始的「字節」的字符串,而不是「二進制」 – Mike
的'%x'格式將不打印'float'因爲調用'printf()的'自動轉換的'float'到'double'(以及比'int'短的任何東西)。當你使用'%e'而不是'%f'時會發生什麼? –
我得到: 'recBuffer = 0x12345678 tempFloat = ************************************** *(1.737824e + 034)' 令人驚歎。它永遠不會在你期望的地方。非常感謝。 –