Search This Blog

Wednesday, June 04, 2008

Bitfield inside a Union

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<<, and & …), so I changed the code to use C bitfields.

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.

0 comments: