tags:

views:

72

answers:

1

Hello,

I have an union X. It's size is 64bits. How can I write (if possible) its declaration if I want to access those 64 bits as:

 1. 4 int16_t: p,q,r,s;
 2. Array of 4 int16_t: a[4]
 3. 2 int32_t: n, m;
 4. Array of 2 int32_t: b[2]
 5. 1 int64_t z;
+3  A: 

something like

union thingie_type {
    struct { int16_t p,q,r,s; };
    int16_t a[4];
    struct { int32_t n,m; };
    int32_t b[2];
    int64_t z;
};
Michael Krelin - hacker
bear in mind that this 'thingie_type' will almost certainly not work as intended. byte alignments will create a nightmare without a substantial amount of architecture dependent command line switches for example.
KevinDTimm
KevinDTimm, true, but it's not about declaration. Well, p, a, n, b and z members are more fairly portable ;-)
Michael Krelin - hacker
My point is that while your solution answers the question, it will almost certainly not work when the OP tries to use it (unless, of course, the machine he compiles on has an 8 bit word)
KevinDTimm
KevinDTimm, of course, it's worth mentioning. And the fact that there may be a useful `#pragma` too ;-)
Michael Krelin - hacker
@ KevinDTimm: could you clarify your point? Won't compiler pack {p,q,r,s} into 64 bits?
buratinas
~buratinas, it is not guaranteed. Unless you do some `#pragma pack` or whatever is good for your compiler.
Michael Krelin - hacker