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;

void build_and_print_packet(uint8_t s, uint8_t c, uint16_t d, uint8_t crc, uint8_t e) {
    Packet reg ; 
    reg.raw[0]=reg.fields.start = s ; 
    reg.raw[1]=reg.fields.command = c ; 
    uint8_t d1 = d &0xFF ; 
    uint8_t d2 = d >>  8;
    reg.raw[2]=reg.fields.data = d1 ; 
    reg.raw[3] = d2 ; 
    reg.raw[4]=reg.fields.crc = crc ; 
    reg.raw[5]=reg.fields.end =e ; 
    for(int i= 0 ;i<6 ; i++){
        printf("%d ", reg.raw[i])  ; 
    }
    

}

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