Samuel Jacob's Weblog

Just another technical blog

Bitfield inside a Union

without comments

When coding Ace physical memory manager, I came to a situation where I have to use lot of bit operations on a integer variable. The code looked little ugly because of the explicit bit operations(left shift

typedef struct struct_x
{
 union
 {
  int all;
  int x:1,y:1,z:30,
 };
};

The above code wasn’t working; debugging further I found that the values for bitfields are not calculated correctly.

After some digging I found that, the bitfield hint is ignored by the compiler since it is directly under union. So the compiler treated the fields x,y,z as separate integer instead of considering as one.

I modified the code to pack the bitfields inside a structure and it worked correctly.

typedef struct struct_x
{
 union
 {
  int all;
  struct
  {
   int x:1, y:1, z:30,
  }_;
 };
};

And yes, just an underscore(_) is a valid identifier.

Written by samueldotj

June 4th, 2008 at 11:05 pm

Posted in C,Programming