嵌入式工程师常见面试题

题目

封装一个用于payload传出的结构体,参考

typedef struct{
    uint8_t header55;
    uint8_t headeraa;
    uint8_t cmd;
    uint8_t cs;
    uint8_t length;
    uint8_t payload[0];
} __attribute__ ((packed)) sPacketHeader_t;

申请一段内存,结构体指针为其赋值,计算cs
将这个包模拟传输到另一个设备(函数代替),还原成结构体
计算这个结构体的cs,看和包内的cs是否一致

#include 
#include 
#include 

typedef unsigned char uint8_t;
typedef unsigned int uint32_t;

void data_transmission(void *buf);
#define Get_Name 1

typedef struct{
    uint8_t header55;
    uint8_t headeraa;
    uint8_t cmd;
    uint8_t cs;
    uint8_t length;
    uint8_t payload[0];
} __attribute__ ((packed)) sPacketHeader_t;

uint8_t getCs(sPacketHeader_t *p){
	uint8_t cs = 0;
	uint32_t i;
	for(i= 0; i< p->length; i++){
		cs += p->payload[i];
	}
	return cs;
}

int main(int argc,char *argv[])
{
	sPacketHeader_t *p;
	p = (sPacketHeader_t *)malloc(sizeof(sPacketHeader_t)+10);
	strcpy(p->payload,"abcde");
	p->header55 = 0x55;
	p->headeraa = 0xaa;
	p->cmd = Get_Name;
	p->length = 5;
	p->cs = getCs(p);
//	p->cs = p->payload[0] +p->payload[1]+p->payload[2] +p->payload[3] +p->payload[4] +p->payload[5] +p->payload[6] +p->payload[7];
	printf("%d\n",p->cs);
	data_transmission(p);
	return 0;
}

void data_transmission(void *buf)
{	//55 aa Get_Name 5 a b c d e
	uint8_t *ps = (uint8_t *)buf;
	sPacketHeader_t *p1 = ps;
	printf("header55 = 0x%x\n",p1->header55);
	printf("headeraa = 0x%x\n",p1->headeraa);
	printf("cmd = 0x%x\n",p1->cmd);
	printf("cs = 0x%x\n",p1->cs);
	printf("length = %d\n",p1->length);
	printf("%s\n",p1->payload);
	uint8_t cs = getCs(p1);
//	p_cs = ps[5] + ps[6] + ps[7] + ps[8] +ps[9] + ps[10] + ps[11] +ps[12];
	printf("cs = 0x%x\n",cs);
	if(cs == p1->cs){
		printf("cs一样\n");
	}
	else{
		printf("cs不一样\n");
	}
}

你可能感兴趣的:(C语言编程每日一练)