Hi group,
I wonder - can anybody tell me if it is safe to make a union like this:
union Event {
unsigned char charData[4];
struct {
unsigned int channel : 4;
unsigned int type : 4;
unsigned int note : 8;
int velocity : 8;
} fields;
};
- "safe" in the way that it is guaranteed that:
* fields.channel will return the 4 MSB of charData[0]
* fields.type will return the 4 LSB of charData[0]
* fields.note will return charData[1]
* fields.velocity will return charData[2]
Obviously, if I allocate the struct myself the compiler will guarantee that
no problems arise regarding alignment etc.
But what if the char data I am to interpret comes from "the framework" and I
have no idea where it is allocated? Imagine a function like this
(implementing a virtual framework function):
void interpretCharData(char *data) {
// will this give me problems?
Event *evt = (Event *)data;
// start using the bit fields of the struct here
}
And how about portability? I'm thinking alignment, endiannes, [insert
portability issue I do not know about yet here]
Thanks in advance!
Best regards,
Mogens