According to the documentation, struct.pack('>I',val)
converts a 32-bit unsigned integer into a string in big-endian format. The equivalent C++ code is straightforward to implement using bit operators and would typically look like this:
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);
}
You can find a plethora of existing functions that convert between different endianness, but none of them in standard C++. For example, the htonl
function, shipped with implementations of BSD networking and standardized by POSIX, returns a number whose in-memory representation is the big-endian version of the given value. Using htonl
, pack_uint32_be
could be implemented as:
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);
}
Both functions assume inclusion of <string>
for std::string
and <cstdint>
(or equivalent) for uint32_t
. The latter function also requires inclusion of arpa/inet.hr
or its Windows equivalent for htonl
.