sizeof reports in units of bytes, so it is not well behaved for bit fields.
C doesn't have a clear standard how bit fields have to be laid out, and in general, you should be extremely cautious about any assumptions, especially if different platforms or
different compilers may come into play.
I usually use manual packing/unpacking schemes, but hide the details in acessor
functions, in those rare circumstances where packing information into integers
at the level of bits is appropriate. The only case where the layout of bit fields
absolutely does matter is writing drivers for hardware.
The order in which bit fields are placed in an integer is independent of the order in which bytes are placed in an integer. Both are implementation details. That is generally not a problem, because memory is only byte addressable, and all hardware preserves the value of a byte during transmissions.
Yet, while bit and byte ordering are theoretically independent of each other, CPU documentations tend to number the bits in the same order as they number the bytes: X86 documentation will refer to the least significant bit as bit 0, while Power documentation will refer to the most significant bit as bit 0. Your compiler writers seem to have chosen the same numbering as the respective documentation.
As such, your only hope of achieving portability, is to do the bit fiddling yourself, defining a flags
variable and a bunch of constants to set/mask the respective bits:
const unsigned char kBit0 = 1 << 0,
kBit1 = 1 << 1,
kBit2 = 1 << 2,
kBit3 = 1 << 3,
kBit4 = 1 << 4,
kBit5 = 1 << 5,
kBit6 = 1 << 6,
kBit7 = 1 << 7,
unsigned char reg = 3;
printf("%d %d %d %d %d %d %d %d\n",
!!(reg & kBit0),
!!(reg & kBit1),
!!(reg & kBit2),
!!(reg & kBit3),
!!(reg & kBit4),
!!(reg & kBit5),
!!(reg & kBit6),
!!(reg & kBit7));
This numbers the bits in little endian fashion, irrespective of the machine. If you want big endian numbering, just define your constants accordingly.
Best Answer
After subtracting 1, you need to & the two values. e.g.
int bitremoved = x & (x-1);
In your example you end up with binary 100.