Extract Packet Fields from Byte Stream

Code

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

typedef struct {
    uint8_t start;
    uint8_t command;
    uint16_t data;
    uint8_t crc;
    uint8_t end;
} Packet;

void print_packet_fields(uint8_t *buffer) {
Packet p;

p.start = *buffer;
p.command = *(buffer+1);
p.data = *(buffer+2)|(*(buffer+3)<<8);
p.crc = *(buffer+4);
p.end = *(buffer+5);

printf("Start: %i\n", p.start);
printf("Command: %i\n", p.command);
printf("Data: %i\n", p.data);
printf("CRC: %i\n", p.crc);
printf("End: %i\n", p.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

 

 

 

Upvote
Downvote
Loading...

Input

165 1 52 18 119 90

Expected Output

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