面试题答案
一键面试#include <stdio.h>
// 使用联合体定义数据结构
union ProtocolHeader {
struct {
unsigned short identifier : 16;
unsigned char type_code : 8;
} fields;
unsigned char raw_data[3];
};
// 打印解析后的值的函数
void printHeader(union ProtocolHeader header) {
printf("Identifier: %hu\n", header.fields.identifier);
printf("Type Code: %hhu\n", header.fields.type_code);
}
你可以使用以下方式调用这个函数:
int main() {
union ProtocolHeader test_header;
// 假设我们有这样一组数据(这里手动设置示例数据)
test_header.raw_data[0] = 0x01;
test_header.raw_data[1] = 0x02;
test_header.raw_data[2] = 0x03;
printHeader(test_header);
return 0;
}