Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union and struct packing problem

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?

like image 230
Earlz Avatar asked Jun 11 '09 02:06

Earlz


Video Answer


1 Answers

Your struct has only 31 bits

like image 137
steve Avatar answered Sep 29 '22 09:09

steve