2013-05-17 428 views
0

我想從一個原始二進制字符串中分配一個浮點數,但我沒有得到我所期望的。將二進制轉換爲浮點數

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()來幫助我)。

+0

我想你的意思是原始的「字節」的字符串,而不是「二進制」 – Mike

+2

的'%x'格式將不打印'float'因爲調用'printf()的'自動轉換的'float'到'double'(以及比'int'短的任何東西)。當你使用'%e'而不是'%f'時會發生什麼? –

+0

我得到: 'recBuffer = 0x12345678 tempFloat = ************************************** *(1.737824e + 034)' 令人驚歎。它永遠不會在你期望的地方。非常感謝。 –

回答

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

%x符是整數有用的,但你傳遞一個float價值的printf。所以輸出不是一個有意義的值。

+0

這樣做! 'recBuffer = 0x12345678 tempFloat = ***************************************(1.737824 e + 034)' 我還是不明白爲什麼%f會返回****,但我很高興memcpy()做我期望的。感謝您的幫助! –

0
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, *(unsigned*)&tempFloat); 
    return 0; 
} 
/* 
recBuffer=0x12345678 
tempFloat=17378244361449504000000000000000000.000000 (0x78563412) 
*/ 
+0

%f仍然給我*******,但使用你的建議: 'printf(「tempFloat =%e(0x%x)\ n」,tempFloat,*(unsigned *)&tempFloat);'允許我得到原始的十六進制值!:'recBuffer = 0x12345678 tempFloat = 1.737824e + 034(0x78563412)'。這幫助我很多,謝謝! –

+0

有趣的。 – BLUEPIXY