Converting float values from big endian to little endian

前端 未结 9 1834
清歌不尽
清歌不尽 2020-11-30 02:40

Is it possible to convert floats from big to little endian? I have a big endian value from a PowerPC platform that I am sendING via TCP to a Windows process (li

相关标签:
9条回答
  • 2020-11-30 03:19

    An elegant way to do the byte exchange is to use a union:

    float big2little (float f)
    {
        union
        {
            float f;
            char b[4];
        } src, dst;
    
        src.f = f;
        dst.b[3] = src.b[0];
        dst.b[2] = src.b[1];
        dst.b[1] = src.b[2];
        dst.b[0] = src.b[3];
        return dst.f;
    }
    

    Following jjmerelo's recommendation to write a loop, a more generic solution could be:

    typedef float number_t;
    #define NUMBER_SIZE sizeof(number_t)
    
    number_t big2little (number_t n)
    {
        union
        {
            number_t n;
            char b[NUMBER_SIZE];
        } src, dst;
    
        src.n = n;
        for (size_t i=0; i<NUMBER_SIZE; i++)
            dst.b[i] = src.b[NUMBER_SIZE-1 - i];
    
        return dst.n;
    }
    
    0 讨论(0)
  • 2020-11-30 03:19

    in some case, especially on modbus: network byte order for a float is:

    nfloat[0] = float[1]
    nfloat[1] = float[0]
    nfloat[2] = float[3]
    nfloat[3] = float[2]
    
    0 讨论(0)
  • 2020-11-30 03:26

    Don't memcpy the data directly into a float type. Keep it as char data, swap the bytes and then treat it as a float.

    0 讨论(0)
提交回复
热议问题