**I left out a very important part that allows you to do what you want, and that part is a struct. If you tried my first code, you would have seen that both Hi and Lo output the same thing. Well with a struct, it will now actually split the memory of the int into Hi and Lo.
Use an array
union myData
{
int Data;
struct bytes
{
byte Lo; // <- notice the order, Lo is first. The explanation to this is because memory is read as Lo to Hi, not Hi to Lo
byte Hi;
}B;
}myBytes[20];
void setup()
{
Serial.begin(115200);
for(byte i = 0; i < 20; i++)
myBytes[i].Data = random(10000,32000);
for(byte j = 0; j < 20; j++)
{
Serial.print(myBytes[j].Data,HEX);
Serial.print(" ");
Serial.print(myBytes[j].B.Hi,HEX);
Serial.print(" ");
Serial.println(myBytes[j].B.Lo,HEX);
}
}
void loop()
{
}
I would also like to point out a new milestone, that this is the very first time I have ever had a reason to use a Union.
Sad, I know.
Here is an example which uses nice property of shift.
Now please explain how would using union improve the code or why is it necessary ?
The Data is unchanged , so this flow
byte bByte = Data >> 8;
.... save hi byte
bByte = Data & 0x00FF;
.... save Lo byte
reuses same bByte variable anyway.
Cheers Vaclav
int Data = 12345;
byte Hi = Data >> 8;
byte Lo = Data & 0x00FF;
Serial.println(Data,HEX);
Serial.println(Hi,HEX);
Serial.println(Lo,HEX);
Serial.println(Data,HEX);
el_supremo:
You don't need to mask the low order byte. This works.
byte Lo = Data;
Pete
Even better, nice and smart way showing you know your stuff.
Still not fully convinced that one needs union to convert say 32 bits to bytes.
Actually I am building 40 bits word from bytes byte by byte anyway.
Cheers
Vaclav