The union
type is similar to a struct
except that each of the members of the element occupy the same memory. If you define a struct
so that it has 2 members -- one 4-byte type and one 4-element array of a single byte type, then you can easily refer to the same data as a whole 4-byte element, or byte-wise as you desire.
union packed_long {
long l;
byte b[4];
};
This is the type, so you have to declare the variable to be of that type:
packed_long mydata;
Now, you have two sub-elements of mydata
: l
and b[]
.
To save your long
value, write to the l
part:
mydata.l = myaccel.getY();
To access each of the 4 bytes:
byte1 = mydata.b[0];
byte2 = mydata.b[1];
byte3 = mydata.b[2];
byte4 = mydata.b[3];
On the receiving end, you take each of the 4 bytes:
mydata.b[0] = canbus.read();
mydata.b[1] = canbus.read();
mydata.b[2] = canbus.read();
mydata.b[4] = canbus.read();
As long as you receive the bytes in the same order in which you sent them, you can now access your long
value in mydata.l
.
The actual size of different types is dependent on the compiler and architecture, so you may also wish to define your value as a definite-sized variable to ensure you are always working with 32 bits: int32_t
(signed 32-bit integer) or uint32_t
(unsigned 32-bit integer).