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

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

    Simply put:

    #include 
    
    template 
    T swap_endian(T u)
    {
        static_assert (CHAR_BIT == 8, "CHAR_BIT != 8");
    
        union
        {
            T u;
            unsigned char u8[sizeof(T)];
        } source, dest;
    
        source.u = u;
    
        for (size_t k = 0; k < sizeof(T); k++)
            dest.u8[k] = source.u8[sizeof(T) - k - 1];
    
        return dest.u;
    }
    

    usage: swap_endian(42).

提交回复
热议问题