All submissions

Extract Packet Fields from Byte Stream

Code

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

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

void print_packet_fields(uint8_t *buffer) {
    // Overlay struct and print values
    Packet *ptr;
    ptr= (Packet *)buffer;
    printf("Start: %u\n", ptr->UART_t.start);
    printf("Command: %u\n", ptr->UART_t.command);
    printf("Data: %u\n", ptr->UART_t.data);
    printf("CRC: %u\n", ptr->UART_t.crc);
    printf("End: %u\n", ptr->UART_t.end);

}

int main() {
    uint8_t buffer[6];
    for (int i = 0; i < 6; i++) {
        scanf("%hhu", &buffer[i]);
    }
    print_packet_fields(buffer);
    return 0;
}

Solving Approach

use a type definition union to overlay the struct with the array of bytes

 

 

Loading...

Input

165 1 52 18 119 90

Expected Output

Start: 165 Command: 1 Data: 4660 CRC: 119 End: 90