I am looking at some c++ code and I want to find out what union is doing to help translate a byte array into, well a different type such as a word. At least that is what I think is going on. Truly what I want is to figure out the purpose for this code, but I think I understand some of it.
My research has brought me bits and pieces of understanding, but I am not confident that I see the big picture correctly.
So lets say I have a union defined as:
typedef union _BYTE_TO_WORD {
BYTE b[2];
WORD w;
short s;
} BYTE_TO_WORD;
Note that the byte here is 8 bits and the Word is an unsigned short and both shorts (signed and unsigned) are 16 bits.
then what happens if in the main code I have a struct....
byte[] data = someData;
struct TWO_WORDS {
_BYTE_TO_WORD word1;
_BYTE_TO_WORD word2;
}*theWordsIWant = (struct TWO_WORDS*)&data;
I think that the code above takes two bytes of data and put it into word1 and then the next two bytes of data are put into word2. With all the information about unions and structs out there, I can't seem to pin down a search that explains this code. If I am wrong here, please tell me.
So if I am right about that, then what in word1 or word2 has the value. So my research says that word1 would have a byte array in it, since it can only hold one value.
The translation must be another part of the code (that I haven't found yet) where we do this (assuming I could cast the byte to a WORD):
theWordsIWant.w = (WORD)theWordsIWant.b;
So then the bonus question is, why go to all this trouble with the union, when you could simply cast it as a different variable?
WORD w = (WORD)theWordsIWant.b;
Perhaps what is really going on is that the code will "cast a pointer to anything" as one answer here suggests (How to convert from byte array to word array in c).
I am pretty sure I am missing something, either in the motivation for doing this, or the way it works. But then again, maybe I actually understand it after all? I don't know. You tell me.