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;
};
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With