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)

(我知道字节序。)

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

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() 来帮助我)。

4

2 回答 2

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

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

于 2013-05-17T19:48:02.997 回答
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)
*/
于 2013-05-17T20:06:16.030 回答