All submissions

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;

// 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) {
   
    uint8_t buffer[100]; // Temporary large buffer
    int pos = 0;         // Position in buffer

    // Fill buffer
    buffer[pos++] = s;                  // Start byte
    buffer[pos++] = c;                  // Command
    buffer[pos++] = d & 0xFF;           // Data low byte
    buffer[pos++] = (d >> 8) & 0xFF;    // Data high byte
    buffer[pos++] = crc;                // CRC
    buffer[pos++] = e;                  // End byte


    for (int i = 0; i < pos; i++) {
        printf("%d ", buffer[i]);
    }
    printf("\n");

}

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

 

 

 

Loading...

Input

165 1 4660 119 90

Expected Output

165 1 52 18 119 90