Union and struct packing problem

Earlz picture Earlz · Jun 11, 2009 · Viewed 9.2k times · Source

I'm writing some software where each bit must be exact(it's for the CPU) so __packed is very important.

typedef union{
uint32_t raw;
struct{
    unsigned int present:1;
    unsigned int rw:1;
    unsigned int user:1;
    unsigned int dirty:1;
    unsigned int free:7;
    unsigned int frame:20;
} __packed;
}__packed page_union_t;

that is my structure and union. It does not work however:

page_union_t p; //.....
//This:
p.frame=trg_page;
p.user=user;
p.rw=rw;
p.present=present;
//and this:
p.raw=trg_page<<12 | user<<2 | rw<<1 | present;

should create the same uint32. But they do not create the same thing.

Is there something I can not see that is wrong with my union?

Answer

steve picture steve · Jun 11, 2009

Your struct has only 31 bits