Packet Layout Using Union with Struct

Code

#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;
Packet p;
// Fill struct fields and print raw bytes
void build_and_print_packet(uint8_t s, uint8_t c, uint16_t d, uint8_t crc, uint8_t e) {
    // Your logic here
    p.fields.start = s;
    p.fields.command = c;
    p.fields.data = d;
    p.fields.crc = crc;
    p.fields.end = e;
    printf("%u %u %u %u %u %u",p.raw[0],p.raw[1],p.raw[2],p.raw[3],p.raw[4],p.raw[5]);

}

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;
}

Solving Approach

  • Define a union that overlays:
    • a struct view of these fields, and
    • a uint8_t[6] array view
  • Accept values for start, command, data (16-bit), CRC, and end
  • Fill the packet struct
  • Print the raw 6-byte array using the byte array view

 

 

Upvote
Downvote
Loading...

Input

165 1 4660 119 90

Expected Output

165 1 52 18 119 90