【问题标题】:Convert big-endian bytes array to int like struct.unpack in python将大端字节数组转换为 int,如 python 中的 struct.unpack
【发布时间】:2021-08-27 12:43:23
【问题描述】:

最近我正在尝试将 python 串行数据分析器转换为 c++,但我面临一个问题,即如何将 feff 转换为 c++ 中的整数 -2,这是我的 python 代码的一部分。

def Control_Message(input_):
    print(input_[4:8])
    print(bytes.fromhex(input_[4:8]))
    print(struct.unpack('h', bytes.fromhex(input_[4:8])))
    print(struct.unpack('h', bytes.fromhex(input_[4:8]))[0])
    Angular_Rate_X = struct.unpack('h', bytes.fromhex(input_[0:4]))[0] * 600 * 2 ** -20

结果是:

feff
b'\xfe\xff'
(-2,)
-2

现在我很困惑,我怎么能在 c++ 中做同样的事情,希望你的帮助,谢谢!

【问题讨论】:

  • 您是否尝试过在您的 C++ 教科书中寻找这样做的示例?你试过什么?此类基本字节操作的示例总是可以在介绍性 C 和 C++ 教科书中找到。
  • @SamVarshavchik 谢谢你的回答!我尝试用谷歌搜索这个解决方案,但我失败了。我是 c++ 新手,我现在就去检查我的 c 入门,
  • @Kniok 当您将 feff 转换为整数时,您会得到 65279。您能解释一下尝试将其转换为 2 的含义吗?
  • @east1000 这正是 2 的补码……我从来没想过。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: python c++


【解决方案1】:
#include <cstdint>
#include <iostream>

int main() {
    uint16_t value = 0xfeff;
    uint8_t firstByte = static_cast<uint8_t>((value & 0xFF00) >> 8);
    uint8_t secondByte = static_cast<uint8_t>(value & 0x00FF);
    std::cout << std::hex << static_cast<int>(firstByte) << "\n";
    std::cout << std::hex << static_cast<int>(secondByte) << "\n";
}

输出:

fe
ff

如果您的目标是分别获取 fe 和 ff,然后将它们视为整数,请执行以下操作。

#include <cstdint>
#include <iostream>

int main() {
    uint16_t value = 0xfeff;
    uint8_t firstByte = static_cast<uint8_t>((value & 0xFF00) >> 8);
    uint8_t secondByte = static_cast<uint8_t>(value & 0x00FF);
    std::cout  << static_cast<int>(firstByte) << "\n";
    std::cout  << static_cast<int>(secondByte) << "\n";
}

输出:

254
255

如果您的目标是找到 feff 的整数值,请执行以下操作

#include <cstdint>
#include <iostream>

int main() {
    uint16_t value = 0xfeff;
    std::cout  << static_cast<int>(value) << "\n";
}

输出:

65279

【讨论】:

  • 感谢您的帮助!我发现我需要的是 little-endian 补码计算,而不是简单的转换。现在我有了解决方案!
  • @Kniok 欢迎您,如果您能将我的答案标记为您问题的答案,我将不胜感激,以便其他人可以更好地从答案中受益。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 2022-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多