面试题答案
一键面试设计思路
- 定义一个联合体,其中包含不同数据帧类型对应的结构体,这些结构体共享联合体的内存空间。
- 定义一个公共的数据帧头结构体,包含标识位用于区分数据帧类型。
- 在接收数据后,首先解析数据帧头,根据标识位确定数据帧类型,然后使用联合体来正确解析对应的数据结构。
关键代码片段
// 公共数据帧头结构体
typedef struct {
unsigned int type : 4; // 假设用4位标识数据帧类型
// 其他公共字段可继续添加
} FrameHeader;
// 数据帧类型1结构体
typedef struct {
FrameHeader header;
int data1;
char data2[10];
} FrameType1;
// 数据帧类型2结构体
typedef struct {
FrameHeader header;
float data3;
short data4;
} FrameType2;
// 数据帧类型3结构体
typedef struct {
FrameHeader header;
long data5;
double data6;
} FrameType3;
// 联合体用于解析不同类型数据帧
typedef union {
FrameType1 type1;
FrameType2 type2;
FrameType3 type3;
} FrameUnion;
// 解析函数示例
void parseFrame(const char* buffer, int length) {
FrameUnion frame;
memcpy(&frame, buffer, length);
switch (frame.type1.header.type) {
case 1:
// 处理FrameType1数据
printf("Frame Type 1: data1 = %d, data2 = %s\n", frame.type1.data1, frame.type1.data2);
break;
case 2:
// 处理FrameType2数据
printf("Frame Type 2: data3 = %f, data4 = %hd\n", frame.type2.data3, frame.type2.data4);
break;
case 3:
// 处理FrameType3数据
printf("Frame Type 3: data5 = %ld, data6 = %lf\n", frame.type3.data5, frame.type3.data6);
break;
default:
printf("Unknown frame type\n");
}
}
在实际应用中,parseFrame
函数的 buffer
参数将是接收到的数据帧内容,length
是数据帧的长度。根据实际协议可能需要更多的错误处理和优化。以上代码以C语言为例,不同编程语言实现方式略有不同,但核心思路一致。