Originally posted by napkin111
Darksaidin: Hmm, I'm not sure about extracting the individual bits from an int (I have little experience with it), but I do know how to use bit fields, and that seems to be the same concept.
It's actually quite simple: Just define a union with enough space for either one integer or 4 bytes:
Code:
typedef union {
int integer;
struct {
byte a,b,c,d;
};
} UIntBytes;
Thats it. d is the highbyte, a the lower one. You can write an int into the integer component and read the results from the a..d bytes or do it the other way round.
The following piece of code is only needed to demonstrate how it works:
Code:
UIntBytes uConv;
uConv.a = 255;
uConv.b = 255;
uConv.c = 0;
uConv.d = 0;
/* only used for sprintf */
char buffer [50];
int nonsense;
/* print the integer as a decimal to a string, cout it */
nonsense = sprintf(buffer, "union as integer: %d", uConv.integer);
cout << buffer << endl;
This code uses anonymous structs within a union. I know anonymous unions within structs are standard C, not sure about structs within unions. If it gives you a compiler message, give the struct a name and access a,b,c and d with unionname.structname.a ... d