克服RPC端序转换

overcome rpc endianness convert

本文关键字:转换 RPC 克服      更新时间:2023-10-16

我想将unsigned char[8]赋值给uint64 (c语言),通过RPC传递该值,并将uint64转换回具有相同字节顺序的unsigned char[8] (cpp语言)。问题是RPC可能会转换我的uint64 endianness。最好的方法是什么?

虽然端烷可能会改变,但您仍然可以从uint64_t中移植地提取单个字节,例如:

void to_bytes(uint64_t from, char* to) {
    for(size_t i = 0; i < sizeof from; ++i, from >>= 8)
        to[i] = from & 0xff;
}

或者,使用反向复制操作:

#ifdef BOOST_LITTLE_ENDIAN
    inline void xcopy(void* dst, void const* src, size_t n)
    {
        char const* csrc = static_cast<char const*>(src);
        std::reverse_copy(csrc, csrc + n, static_cast<char*>(dst));
    }
#elif defined(BOOST_BIG_ENDIAN)
    inline void xcopy(void* dst, void const* src, size_t n)
    {
        char const* csrc = static_cast<char const*>(src);
        std::copy(csrc, csrc + n, static_cast<char*>(dst));
    }
#endif
void to_bytes(uint64_t from, char* to) {
    xcopy(to, &from, sizeof from);
}
void from_bytes(char const* from, uint64_t* to) {
    xcopy(to, from, sizeof *to);
}
unit8_t data[8];
// fill the array, then ...
uint64_t carrier = data [0];
size_t position;
for (position = 1; position < 8; ++position) {
  carrier <<= 8;
  carrier |= data[position];
}
// ... on the other end
// variables of same type
position = 8;
while (position--) {
  data[position] = 0xFF & carrier;
  carrier >>= 8;
}

应该这样做,因为carrier(因此您不必担心端序)将(希望)由RPC协议正确传输。注意使用uint8_t而不是char。后者不能保证是uint64_t的1/8。

代码应该在C和c++中都有良好定义的行为。对于c++,您应该使用std::array而不是原始数组。