質問

I have Python code struct.pack('>I',val) where val is any number, how can i do this in C++.

I know struct.pack return byte string in Big-endian byte-order in unsigned int, if set '>I', but how i do that in C++.

I understand that full analog of this function dosent exist in C++, but maybe i can do this with some C++ code? Thanks!

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top