Converting Endianess on a bit field structure

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

    In a project porting code from MIPS to Linux/x86 we did like this.

    struct {
    
    #ifdef __ONE_ENDIANESS__
        unsigned int    b1:1;
        unsigned int    b2:8;
        unsigned int    b3:7;
        unsigned int    b4:8;
        unsigned int    b5:7;
        unsigned int    b6:1;
    #define _STRUCT_FILLED
    #endif /* __ONE_ENDIANESS__ */
    
    #ifdef __OTHER_ENDIANESS__
        unsigned int    b6:1;
        unsigned int    b5:7;
        unsigned int    b4:8;
        unsigned int    b3:7;
        unsigned int    b2:8;
        unsigned int    b1:1;
    #define _STRUCT_FILLED
    #endif /* __OTHER_ENDIANESS__ */
    
    };
    
    #ifndef _STRUCT_FILLED
    #  error Endianess uncertain for struct
    #else
    #  undef _STRUCT_FILLED
    #endif /* _STRUCT_FILLED */
    

    The macros __ONE_ENDIANESS__ and __OTHER_ENDIANESS__ was the appropriate for the compiler we used so you might need to look into which is appropriate for you...

提交回复
热议问题