You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将char数组转换为float时遇异常问题求助

char数组转float时出现-nan的问题解决

需要将两个16位值A=7C37、B=428B排列为大端序float字节序列42 8B 7C 37,对应浮点值69.74261,但现有转换代码得到了-nan的异常结果,输出显示raw值为0xff8b7c37。

原代码如下:

#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;
}

问题原因

  1. 符号扩展问题:char在多数编译环境下是有符号类型,当pData[7]的值为0x8b时,会被解析为有符号的-117,转换为uint32_t时会触发符号扩展,填充高位为0xff,最终导致raw的高位字节错误地变成0xff。
  2. 字节拼接顺序错误:原代码的字节拼接逻辑没有对应大端序的42 8B 7C 37,正确的大端序32位值应该是0x428B7C37,高位字节0x42对应左移24位,0x8b左移16位,0x7c左移8位,0x37作为最低位。

解决方案

  1. 将数组类型改为uint8_t(无符号字节类型),避免符号扩展。
  2. 调整字节拼接顺序,匹配大端序的字节排列。

修正后的代码:

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

int main() {
    // 改用uint8_t避免符号扩展
    uint8_t pData[8] = {0x00, 0x00, 0x00, 0x00, 0x7c, 0x37, 0x42, 0x8b};
    float floatValue;
    uint32_t raw;

    // 按照大端序拼接:42(字节6) <<24 | 8B(字节7) <<16 |7C(字节4) <<8 |37(字节5)
    raw = ((uint32_t)pData[6]) << 24 | ((uint32_t)pData[7]) << 16 |
          ((uint32_t)pData[4]) << 8  | ((uint32_t)pData[5]);

    memcpy(&floatValue, &raw, sizeof(floatValue));

    printf("The float value is: %.5f\nThe raw value is 0x%x\n", floatValue, raw);
    return 0;
}

运行结果

修正后的代码会输出:

The float value is: 69.74261
The raw value is 0x428b7c37

内容的提问来源于stack exchange,提问作者stdcerr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 12:27:27