我有 Python 代码 struct.pack('>I',val)
其中 val
是任意数字,我如何在 C++ 中执行此操作。
我知道 struct.pack
如果设置 '>I',则以 unsigned int 的大端字节顺序返回字节字符串,但我如何在 C++ 中做到这一点。
我知道这个函数的完整模拟存在于 C++ 中,但也许我可以用一些 C++ 代码来做到这一点?谢谢!
最佳答案
根据 the documentation , 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++ 中没有一个。例如, htonl
函数,随 BSD 网络的实现一起提供并由 POSIX 标准化,返回一个数字,其在内存中的表示是给定值的大端版本。使用 htonl
, pack_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);
}
这两个函数都假定包含 <string>
对于 std::string
和 <cstdint>
(或等效)uint32_t
.后一个功能还需要包含 arpa/inet.hr
或其 Windows 等效项 htonl
.
关于用于执行 Python struct.pack ('>I' ,val 的 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21180078/