Converting float values from big endian to little endian

前端 未结 9 1849
清歌不尽
清歌不尽 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

提交回复
热议问题