Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Endianess on a bit field structure

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 swap the structure elements.

Ex Structure is:

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;
}; 
like image 491
foo Avatar asked Apr 07 '09 06:04

foo


2 Answers

You could use a 32 bit integer, and extract information out of it using and- and bitshift operators. With that in place, you could simply use htonl (host-to-network, long). Network byte order is big endian.

This won't be as elegant as a bit-field, but at least you'll know what you have and won't have to worry about the compiler padding your structures.

like image 74
falstro Avatar answered Nov 10 '22 09:11

falstro


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.

like image 39
Tim Avatar answered Nov 10 '22 07:11

Tim