C++ code for do Python struct.pack('>I',val)

C++ code for do Python struct.pack('>I',val)

本文关键字:gt val for code do Python pack struct C++      更新时间:2023-10-16

我有 Python 代码struct.pack('>I',val)其中val是任何数字,我如何在C++中做到这一点。

我知道struct.pack如果设置为">I",则在无符号整数中以大端字节顺序返回字节字符串,但是我如何在C++中做到这一点。

我知道这个函数的完整模拟存在于C++中,但也许我可以用一些C++代码来做到这一点?谢谢!

根据文档,struct.pack('>I',val)将 32 位无符号整数转换为大端格式的字符串。等效C++代码很容易使用位运算符实现,通常如下所示:

std::string pack_uint32_be(uint32_t val) {
    unsigned char packed[4];
    packed[0] = val >> 24;
    packed[1] = val >> 16 & 0xff;
    packed[2] = val >> 8 & 0xff;
    packed[3] = val & 0xff;
    return std::string(packed, packed + 4);
}

您可以找到大量在不同字节序之间进行转换的现有函数,但在标准C++中没有一个。例如,BSD 网络实现附带并由 POSIX 标准化的 htonl 函数返回一个数字,其内存中的表示形式是给定值的大端版本。使用htonlpack_uint32_be可以实现为:

std::string pack_uint32_be(uint32_t val) {
    uint32_t packed_val = htonl(val);
    auto packed_ptr = reinterpret_cast<const char *>(&packed_val);
    return std::string(packed_ptr, packed_ptr + 4);
}

这两个函数都假定包含std::string<string>uint32_t<cstdint>(或等效项)。后一个功能还需要包含arpa/inet.hr或其Windows等效项htonl