Converting Endianess on a bit field structure

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

    Processor endianness is unrelated to bit field ordering. It's quite possible to have two compilers on the same computer use opposite ordering for bitfields. So, given this:

    union {
        unsigned char x;
        struct {
            unsigned char b1 : 1;
            unsigned char b2 : 7;
        };
    } abc;
    abc.x = 0;
    abc.b1 = 1;
    printf( "%02x\n", abc.x );
    

    Unless you happen to have detailed documentation, the only way to know whether that will print out 01 or 80 is to try it.

提交回复
热议问题