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

前端 未结 30 3263
难免孤独
难免孤独 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-21 23:57

    If you have C++ 17 then add this header

    #include 
    

    Use this template function to swap the bytes:

    template 
    void swapEndian(T& buffer)
    {
        static_assert(std::is_pod::value, "swapEndian support POD type only");
        char* startIndex = static_cast((void*)buffer.data());
        char* endIndex = startIndex + sizeof(buffer);
        std::reverse(startIndex, endIndex);
    }
    

    call it like:

    swapEndian (stlContainer);
    

提交回复
热议问题