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

如何在C++中实现类似Python struct.unpack的字节数组转整型功能

C++实现Python struct.unpack('h') 等效功能的方法

首先明确你场景中struct.unpack('h', buf)的行为:将长度为2字节的小端字节序列解析为有符号16位整数(int16_t),你的示例中b'\xfe\xff'按小端组合得到0xfffe,对应有符号16位整数的补码值就是-2。

以下是无平台依赖的实现方案,不需要依赖系统字节序转换接口:

#include <iostream>
#include <string>
#include <cstdint>
#include <stdexcept>
#include <cmath>

// 十六进制字符转对应数值
uint8_t hex_char_to_byte(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return 10 + c - 'a';
    if (c >= 'A' && c <= 'F') return 10 + c - 'A';
    throw std::invalid_argument("无效十六进制字符");
}

// 等效struct.unpack('h', bytes.fromhex(hex_str))
int16_t unpack_h_from_hex(const std::string& hex_str) {
    if (hex_str.size() != 4) {
        throw std::invalid_argument("解析short类型需要4位十六进制字符串");
    }
    // 十六进制字符串转两个原始字节
    uint8_t low_byte = hex_char_to_byte(hex_str[0]) * 16 + hex_char_to_byte(hex_str[1]);
    uint8_t high_byte = hex_char_to_byte(hex_str[2]) * 16 + hex_char_to_byte(hex_str[3]);
    // 小端序组合为有符号16位整数
    return static_cast<int16_t>((static_cast<uint16_t>(high_byte) << 8) | static_cast<uint16_t>(low_byte));
}

int main() {
    // 测试你的示例输入
    std::string test_hex = "feff";
    int16_t res = unpack_h_from_hex(test_hex);
    std::cout << test_hex << std::endl;
    std::cout << res << std::endl; // 输出-2

    // 对应原Python的角速度计算逻辑
    double Angular_Rate_X = res * 600.0 * pow(2, -20);
    return 0;
}

运行输出:

feff
-2

如果你的串口数据为大端序,只需要调换代码中low_byte和high_byte的组合顺序即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:27:03