将 char 数组转换为 float 时出现意外问题

问题描述 投票:0回答:1

我有一个 char 数组,需要将其转换为 float。 我有两个 16 位值: A = 7C37 B = 428B 它们需要像 42 8B 7C 37 一样排列来代表浮点数中的 69.743,但我很难到达那里,我尝试了以下方法:

#include <stdio.h>
#include <stdint.h>
#include <string.h>

int main() {
    char pData[8] = {0x00, 0x00, 0x00, 0x00, 0x7c, 0x37, 0x42, 0x8b};
    float floatValue;
    uint32_t raw;

    raw = ((uint32_t)pData[5]) | (((uint32_t)pData[4])<<8) | (((uint32_t)pData[7])<<16) | (((uint32_t)pData[6])<<24);

    // Copy the bytes in the correct order into the float variable
    memcpy(&floatValue, &raw, sizeof(floatValue));

    // Print the float value
    printf("The float value is: %f\nThe raw value is 0x%x\n", floatValue,raw);

    return 0;
}

但我很困惑,因为这意外地产生了以下输出:

The float value is: -nan
The raw value is 0xff8b7c37

我认为

-nan
可能会因为最左边的字节中的 0xff 而显示,它应该设置为
0x42
,任何人都可以帮助我吗?

更新: 我基本上想实现来自 https://www.scadacore.com/tools/programming-calculators/online-hex-converter/Float - Big Endian (ABCD),其中 428B7C37 产生 69.74261

c floating-point type-conversion
1个回答
0
投票

我需要将字符压缩成32位uint,然后就这么简单:

#include <stdio.h>

union FloatIntUnion {
    float f;
    unsigned int i;
};

int main() {
    union FloatIntUnion fiu;
    fiu.i = 0x428B7C37; // Set the integer value
    printf("%f\n", fiu.f); // Interpret the bit pattern as a float and print it
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.