Packet Layout Using Union with Struct

Code

#include <stdio.h>
#include <stdint.h>

typedef union{
    uint8_t view[6];
    struct {
        uint8_t start;
        uint8_t command;
        uint16_t data;
        uint8_t crc;
        uint8_t end;
    } fields;
}Packet;


void build_and_print_packet(uint8_t start, uint8_t cmd, uint16_t data, uint8_t crc, uint8_t end){
    // Your logic here
    Packet packet;
    packet.fields.start = start;
    packet.fields.command = cmd;    
    packet.fields.data = data;
    packet.fields.crc = crc;
    packet.fields.end = end;

    for(int i = 0; i < 6; i++){
        printf("%hu", packet.view[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;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

165 1 4660 119 90

Expected Output

165 1 52 18 119 90