#include <stdio.h>
#include <stdint.h>
typedef union {
struct {
uint8_t start;
uint8_t command;
uint16_t data;
uint8_t crc;
uint8_t end;
} fields;
uint8_t raw[6];
} Packet;
void build_and_print_packet(uint8_t s, uint8_t c, uint16_t d, uint8_t crc, uint8_t e) {
Packet p;
// Assign struct fields
p.fields.start = s;
p.fields.command = c;
p.fields.data = d; // stored in little-endian
p.fields.crc = crc;
p.fields.end = e;
// Print raw packet
for (int i = 0; i < 6; i++) {
printf("%u", p.raw[i]);
if(i < 5){
printf(" ");
}
}
}
int main() {
uint8_t s, c, crc, e;
uint16_t d;
scanf("%hhu %hhu %hu %hhu %hhu", &s, &c, &d, &crc, &e);
build_and_print_packet(s, c, d, crc, e);
return 0;
}
In embedded protocols (UART, SPI, BLE), a packet layout is typically defined with clear fields. But for transmission, we often need to view and operate on the entire raw memory — a union provides both access modes.
Solution Logic:
Input
165 1 4660 119 90
Expected Output
165 1 52 18 119 90