이런 구조체 있다고 가정해보자.
typedef struct _ctp_t {
uint8_t head;
uint8_t body[5];
uint8_t tail;
} ctp_t;
#define CTP_SIZE (7)
void print_ctp(const ctp_t* ctp) {
printf("%02X ", ctp->head);
for (int i = 0; i < CTP_SIZE - 2; i++) {
printf("%02X ", ctp->body[i]);
}
printf("%02X ", ctp->tail);
}
수신 데이터를 어떻게 ctp에 넣을것인가?
넣는게 어렵지는 않지만 여간 번거롭다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main() {
// 받은 데이터
uint8_t rx_data[CTP_SIZE] = { 0xAA, 0x12, 0x13, 0x14, 0x15, 0x16, 0xBB };
ctp_t ctp = {0, };
//memcpy(ctp, rx_data, CTP_SIZE); // 구조체로 memcpy는 안되나?
ctp.head = rx_data[0];
ctp.body[0] = rx_data[1];
ctp.body[1] = rx_data[2];
ctp.body[2] = rx_data[3];
ctp.body[3] = rx_data[4];
ctp.body[4] = rx_data[5];
ctp.tail = rx_data[6];
print_ctp(&ctp);
return 0;
}
공용체내에 구조체를 가지면
파싱을 할 필요가 없다!
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define CTP_SIZE (7)
typedef union _ctp_t {
uint8_t all[CTP_SIZE];
struct {
uint8_t head;
uint8_t body[5];
uint8_t tail;
} subset;
} ctp_t;
void print_ctp(const ctp_t* ctp) {
//printf("%02X ", ctp->head);
for (int i = 0; i < CTP_SIZE; i++) {
printf("%02X ", ctp->all[i]);
}
//printf("%02X ", ctp->tail);
}
int main() {
// 받은 데이터
uint8_t rx_data[CTP_SIZE] = { 0xBB, 0x12, 0x13, 0x14, 0x15, 0x16, 0xAA };
ctp_t ctp = {0, };
memcpy(ctp.all, rx_data, CTP_SIZE); // 구조체로 memcpy는 안되나?
//ctp.head = rx_data[0];
//ctp.body[0] = rx_data[1];
//ctp.body[1] = rx_data[2];
//ctp.body[2] = rx_data[3];
//ctp.body[3] = rx_data[4];
//ctp.body[4] = rx_data[5];
//ctp.tail = rx_data[6];
print_ctp(&ctp);
return 0;
}
다음과 같은 데이터를 받았다 “1212121212ABCD9876”