#include <stdio.h> #include <stdint.h> #include <cstring> 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 *p = (Packet*)buffer; this also works Packet pac; // pac.start = *(buffer+0); // pac.command = *(buffer+1); // pac.data = buffer[2] | (buffer[3] << 8); // pac.crc = *(buffer+4); // pac.end = *(buffer+5); memcpy(&pac , buffer , 6) ; printf("Start: %hhu\n", pac.start); printf("Command: %hhu\n", pac.command); printf("Data: %hu\n", pac.data); printf("CRC: %hhu\n", pac.crc); printf("End: %hhu\n", pac.end); // printf("Start: %hhu\n",pac.start ); // printf("Command: %hhu\n",pac.command ); // printf("Data: %hhu\n",pac.data ); // printf("CRC: %hhu\n",pac.crc ); // printf("End: %hhu\n",pac.end ); } int main() { uint8_t buffer[6]; for (int i = 0; i < 6; i++) { scanf("%hhu", &buffer[i]); } print_packet_fields(buffer); return 0; }
Test Cases
Test Results
Input
165 1 52 18 119 90
Expected Output
Start: 165 Command: 1 Data: 4660 CRC: 119 End: 90