Converting Endianess on a bit field structure

前端 未结 8 831
心在旅途
心在旅途 2021-02-02 03:48

I need to convert a bit-field structure from little-endian to big-endia architecture. What is the best way to do that, as there will be issues in byte boundaries, if I simply sw

8条回答
  •  渐次进展
    2021-02-02 04:15

    To get this going I finally got a solution (some what derived from epatel's solution above). This is if I convert from x86 to Solaris SPARC.

    We need to first swap the incoming sturcture and then read the elements in reverse order. Basically after looking at how the structures are alligned I saw that the endianess changed both in byte ordering and bit ordering. Here is a pseudo code.

    struct orig
    {    
        unsigned int    b1:1;
        unsigned int    b2:8;
        unsigned int    b3:7;
        unsigned int    b4:8;
        unsigned int    b5:7;
        unsigned int    b6:1;
    };
    
    struct temp
    {    
        unsigned int    b6:1;
        unsigned int    b5:7;
        unsigned int    b4:8;
        unsigned int    b3:7;
        unsigned int    b2:8;
        unsigned int    b1:1;
    }temp;
    
    
    func (struct orig *toconvert)
    {
        struct temp temp_val;
        //Swap the bytes
        swap32byte((u32*)toconvert);
        //Now read the structure in reverse order - bytes have been swapped
        (u32*)&temp_val = (u32 *)toconvert;
        //Write it back to orignal structure
        toconvert->b6=temp_val.b6;
        toconvert->b5=temp_val.b5;
        toconvert->b4=temp_val.b4;
        toconvert->b3=temp_val.b3;
        toconvert->b2=temp_val.b2;
        toconvert->b1=temp_val.b1;
    

    }

    After some experimenting I found that this approach is only valid if the elements completely fill the structure, i.e. there are no unused bits.

提交回复
热议问题