Converting Endianess on a bit field structure

前端 未结 8 667
心在旅途
心在旅途 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:18

    You have two 16 bit sections there (the first three fields and the last three fields are 16 bits).

    That's only 65536 entries. So have a lookup table that holds the bit-reversed version of the fields. Wrap the struct in a union with another struct that has two 16 bit fields to make this easier?

    Something like (untested, I'm not near a C compiler):

    union u {
        struct {
            unsigned int    b1:1;
            unsigned int    b2:8;
            unsigned int    b3:7;
            unsigned int    b4:8;
            unsigned int    b5:7;
            unsigned int    b6:1;
         } bits;
         struct {
            uint16 first;
            uint16 second;
         } words
    } ;
    
    unit16 lookup[65536];
    
    /* swap architectures */
    
    void swapbits ( union u *p)
    {
       p->words.first = lookup[p->words.first];
       p->words.second = lookup[p->words.second];
    }
    

    Population of the lookup table left as an exercise for the reader :)

    However, read your compiler doc carefully. I'm not sure if the C standard requires that struct to fit in a word (although I'd expect most compilers to do that).

提交回复
热议问题