How can I get bitfields to arrange my bits in the right order?

Posted by Jim Hunziker on Stack Overflow See other posts from Stack Overflow or by Jim Hunziker
Published on 2010-04-19T01:37:28Z Indexed on 2010/04/19 1:43 UTC
Read the original article Hit count: 348

Filed under:
|
|
|

To begin with, the application in question is always going to be on the same processor, and the compiler is always gcc, so I'm not concerned about bitfields not being portable.

gcc lays out bitfields such that the first listed field corresponds to least significant bit of a byte. So the following structure, with a=0, b=1, c=1, d=1, you get a byte of value e0.

struct Bits {
  unsigned int a:5;
  unsigned int b:1;
  unsigned int c:1;
  unsigned int d:1;
} __attribute__((__packed__));

(Actually, this is C++, so I'm talking about g++.)

Now let's say I'd like a to be a six bit integer.

Now, I can see why this won't work, but I coded the following structure:

struct Bits2 {
  unsigned int a:6;
  unsigned int b:1;
  unsigned int c:1;
  unsigned int d:1;
} __attribute__((__packed__));

Setting b, c, and d to 1, and a to 0 results in the following two bytes:

c0 01

This isn't what I wanted. I was hoping to see this:

e0 00

Is there any way to specify a structure that has three bits in the most significant bits of the first byte and six bits spanning the five least significant bits of the first byte and the most significant bit of the second?

Please be aware that I have no control over where these bits are supposed to be laid out: it's a layout of bits that are defined by someone else's interface.

© Stack Overflow or respective owner

Related posts about gcc

Related posts about bitfields