All submissions

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) {
    // Overlay struct and print values

    Packet input;
    input.start=buffer[0];
    input.command=buffer[1];
    ////Initially put byte1  which forms the lowerbyte of 16 bit data.
    input.data=buffer[2];
    //Now,we need to put byte2 data on higher byte side, hence we need to leftshift by 8 times.
    input.data=((input.data)|(buffer[3]<<8));
    input.crc=buffer[4];
    input.end=buffer[5];

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

 

 

 

Loading...

Input

165 1 52 18 119 90

Expected Output

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