I am trying to cast a byte stream (raw data from serial port) into a structure for ease of use. I have managed to replicate the problem in a minimal working example:
#include <stdio.h>
typedef struct {
unsigned int source: 4;
unsigned int destination: 4;
char payload[15];
} packet;
int main(void)
{
// machine 9 sends a message to machine 10 (A)
char raw[20] = {0x9A, 'H', 'e', 'l', 'l', 'o', '!', 0};
packet *message = (packet *)raw;
printf("machine %d ", message->source);
printf("says '%s' to ", message->payload);
printf("machine %d.\n", message->destination);
return 0;
}
I would expect the field source
to get 9
from 0x9A
and destination
to get A
from 0x9A
so that the output says:
machine 9 says 'Hello!' to machine 10.
But I get:
machine 10 says 'Hello!' to machine 9.
Any idea why this might be so?