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

前端 未结 30 2514
难免孤独
难免孤独 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:12

    Here's a generalized version I came up with off the top of my head, for swapping a value in place. The other suggestions would be better if performance is a problem.

     template
        void ByteSwap(T * p)
        {
            for (int i = 0;  i < sizeof(T)/2;  ++i)
                std::swap(((char *)p)[i], ((char *)p)[sizeof(T)-1-i]);
        }
    

    Disclaimer: I haven't tried to compile this or test it yet.

提交回复
热议问题