I have a C program that receives a 64 byte array of char (which is passed via USB). Depending on the first byte (which indicates the command type) I want to ‘impose’ a structure over the char array to make the code clearer.
For example, if the command code is 10 I would expect something like:
struct
{
uint8_t commandNumber;
uint16_t xPos;
uint16_t yPos;
int32_t identificationNumber;
} commandTen;
So I would like to cast my char packet[64] ‘onto’ commandTen and then access the fields using something like:
localVar = commandTenPacket->xPos;
How can this be achieved in C?
Thanks in advance!
First, as others said you’d have to ensure that your
structhas no padding. Your compiler probably has an extension for that,#pragma packor so.Define a
structfor each of your use cases, not a variable as in your example.Then define a
unionNow create a buffer of that type
Feed the “raw” part to your function that receives the data:
getit(buffer.raw). And thenThis is guaranteed by the C standard to work well, since you are reading everything as
uint8_tAKAunsigned char. In fact, the principle use case forunions is just this sort of “type puning”. The whole network layer with it different types of IPv4, IPv6 etc addresses works in a similar way.