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

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

    Just thought I added my own solution here since I haven't seen it anywhere. It's a small and portable C++ templated function and portable that only uses bit operations.

    template inline static T swapByteOrder(const T& val) {
        int totalBytes = sizeof(val);
        T swapped = (T) 0;
        for (int i = 0; i < totalBytes; ++i) {
            swapped |= (val >> (8*(totalBytes-i-1)) & 0xFF) << (8*i);
        }
        return swapped;
    }
    

提交回复
热议问题