deserialize char Array to int and int[] and struct?
Can I populate a struct
by treating it as an array of unsigned char
values?
I receive character data over the RS232 UART from a Microcontroller. Using C, how can I deserialize the char Array in my Datatypes uint16_t, uin32_t, int32_t[], …
e.g.
uin16_t StartID = ARRAY[0]; uin16_t EndID = ARRAY[246];
… is there something like this ? In C# there are effective functions for deserialization but im not that in C
for later
if (StartID == 11) printf("good"); else printf("bad");
I made this struct to work easier later with the Data. Is there a way to get the Data from my ARRAY[248] into my struct?
typedef struct { //Header 6byte uint16_t StartID; // Check if its 1 or in hex 0b uint16_t ID; uint16_t LoadID; //Payload 240 byte int32_t POS01[3]; int32_t POS02[3]; int32_t POS03[3]; int32_t POS04[3]; int32_t POS05[3]; int32_t POS06[3]; int32_t POS07[3]; int32_t POS08[3]; int32_t POS09[3]; int32_t POS10[3]; int32_t POS11[3]; int32_t POS12[3]; int32_t POS13[3]; int32_t POS14[3]; int32_t POS15[3]; int32_t POS16[3]; int32_t POS17[3]; int32_t POS18[3]; int32_t POS19[3]; int32_t POS20[3]; //End 2byte uint16_t EndID; // Check if its 47 or in hex 2F } DATA_POS; //TOTAL = 248byte
Answer
C has a feature called pointers
:
uin16_t *StartID = (void*)&ARRAY[0]; uin16_t *EndID = (void*)&ARRAY[246];
Other means to access data under another format include unions
:
union { uint32_t *u32; uint16_t *u16; uint8_t *u8; } u;
As you can see, sometimes features do not need a dedicated function.
Beware however that alignment issues could arise on some platforms because of accessing data in such a way.