How do I convert between big-endian and little-endian values in C++?

前端 未结 30 2550
难免孤独
难免孤独 2020-11-21 23:18

How do I convert between big-endian and little-endian values in C++?

EDIT: For clarity, I have to translate binary data (double-precision floating point values and 3

30条回答
  •  广开言路
    2020-11-22 00:16

    We've done this with templates. You could do something like this:

    // Specialization for 2-byte types.
    template<>
    inline void endian_byte_swapper< 2 >(char* dest, char const* src)
    {
        // Use bit manipulations instead of accessing individual bytes from memory, much faster.
        ushort* p_dest = reinterpret_cast< ushort* >(dest);
        ushort const* const p_src = reinterpret_cast< ushort const* >(src);
        *p_dest = (*p_src >> 8) | (*p_src << 8);
    }
    
    // Specialization for 4-byte types.
    template<>
    inline void endian_byte_swapper< 4 >(char* dest, char const* src)
    {
        // Use bit manipulations instead of accessing individual bytes from memory, much faster.
        uint* p_dest = reinterpret_cast< uint* >(dest);
        uint const* const p_src = reinterpret_cast< uint const* >(src);
        *p_dest = (*p_src >> 24) | ((*p_src & 0x00ff0000) >> 8) | ((*p_src & 0x0000ff00) << 8) | (*p_src << 24);
    }
    

提交回复
热议问题