I am learning the union and struct and I wrote the code below. What I do not understand is why the output is different when I change from a little endian to a big endian machine.
My understanding is that endianness is important when you have more than one byte. But I have only 8 bits.
This code is not portable at this time and I want to understand how to make it portable. I would like to avoid detecting the endianness or using bit shifting techniques. I know about htonX functions but I do not think that applies here.
#include <stdio.h>
int main()
{
typedef union {
struct {
unsigned char b0:1;
unsigned char b1:1;
unsigned char b2:1;
unsigned char b3:1;
unsigned char b4:1;
unsigned char b5:1;
unsigned char b6:1;
unsigned char b7:1;
} bits;
unsigned char byte;
} HW_Register;
HW_Register reg;
reg.byte = 3;
printf("%d %d %d %d %d %d %d %d\n",
reg.bits.b0,
reg.bits.b1,
reg.bits.b2,
reg.bits.b3,
reg.bits.b4,
reg.bits.b5,
reg.bits.b6,
reg.bits.b7);
printf("%d\n",reg.byte);
printf("Size of reg.byte: %d\n", sizeof(reg.byte));
}