converting between classes

Hello,

I am currently working on a college project which involves the use of RF packet transmission. Each packet contains 32 bytes of information and each packet will contain different instructions/commands for the system as a whole.

Currently i was thinking of using classes to store each packet and to determine what to do with it however i have a question about type casting / union between differet classes.

i currently have a general class which contains a 32 byte array, so when the data is received from the RF transmission it is saved into this class as general data. like so:

1
2
3
4
class MSG
{
byte msgData[32];
};


If i was to create another class which contained a variable and the rest of the data as an array in which totals up to 32 bytes like:

1
2
3
4
5
class MSGTYPE
{
short msgType;
byte msgData[31];
};


would i be able to union these two together so that i can switch between them? if so when i switch between then would the 1st element in the MSG class msgData become the msgType in the MSGTYPE class? and the elements left in the 32 byte array would be loaded into the array of 31 bytes.

am I correct in saying this or have i got the wrong idea completely?

thanks,

edit:

while I remember I typedef an unsigned char to be a byte
Last edited on
No magical data conversion will happen. Since short has more than one byte MSGTYPE will have more than 32 bytes.

if short has 2 bytes and MSGTYPE is use in a union with MSG msgType will contain the first 2 bytes.
ah ok, i though it had 1 byte of data :)

if i had the width of the variable correct they would translate accross.

will this work with multiple variables swell so a class with two short data types and an array to pad out the rest would have the first two elements go into the first short variable and then the next two into the 2nd short variable then the rest into a 28 byte array. is this correct?

assuming the class was created like so:
1
2
3
4
5
6
class MSGTYPE
{
short msgType;
short fromAddress;
byte msgData[28];
};
Last edited on
is this correct?
Yes, but you might get a problem with endianess:

http://en.wikipedia.org/wiki/Endianness

By the way: You don't need 'to pad out the rest'. A union will have the size of the largest object.
I will be running the code on a little endian system. would this cause me any problems?
It depends on how the data is transmitted. For tcp/ip there are specific function for this:

http://linux.die.net/man/3/htons

If you have full control of the byte order there should be no problem.
I believe I do have control as to what byte gets sent first as i have control if the MSB or LSB gets sent first.

thank you for your help.
Topic archived. No new replies allowed.