I was recently playing around with bit fields in C, and apparently, the bits are ordered from low to high, although Google does not support this thesis (e.g. Wikipedia.)
Take the following code (http://ideone.com/UwWfJM):
#include <stdio.h>
struct bits {
unsigned char a : 1;
unsigned char b : 1;
unsigned char c : 1;
unsigned char d : 1;
unsigned char e : 1;
unsigned char f : 1;
unsigned char g : 1;
unsigned char h : 1;
};
int main(int argc, char **argv)
{
unsigned char c = 33;
struct bits *b = (struct bits *) &c;
printf("dec: %u\n", c);
printf("bits: %x", b->a);
printf("%x", b->b);
printf("%x", b->c);
printf("%x", b->d);
printf("%x", b->e);
printf("%x", b->f);
printf("%x", b->g);
printf("%x\n", b->h);
return 0;
}
The output is
dec: 33
bits: 10000100
...although I had expected the bit ordering to be the other way around (i.e. 00100001
, with the MSB in the first place and the LSB in the last place).
Can somebody explain this behaviour?
Furthermore, can I assume that the mapping will always be in this direction?
Note: I am not asking about endianness, which is about the byte order. The background of my question is that I tried to map a buffer to a struct. The buffer contained a UDP message, consisting of a "bit mapping" (i.e. "bit at position x means this, bits at position y to z mean that, and so on).
Thanks!