How to manage endianess of double from network

前端 未结 3 1947
迷失自我
迷失自我 2020-12-18 09:32

I have a BIG problem with the answer to this question Swap bits in c++ for a double

Yet, this question is more or less what I search for: I receive a double from th

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-18 09:51

    Assuming you have a compile-time option to determine endianness:

    #if BIG_ENDIAN
    template 
    void swap_endian(T& pX)
    {
       // Don't need to do anything here... 
    }
    #else
    template 
    void swap_endian(T& pX)
    {
        char& raw = reinterpret_cast(pX);
        std::reverse(&raw, &raw + sizeof(T));
    }
    #endif
    

    Of course, the other option is to not send double across the network at all - considering that it's not guaranteed to be IEEE-754 compatible - there are machines out there using other floating point formats... Using for example a string would work much better...

提交回复
热议问题