mavlink协议CRC校验

 1 // ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
 2 //
 3 
 4 #include <iostream>
 5 #define X25_INIT_CRC 0xffff
 6 inline void crc_accumulate(uint8_t data, uint16_t *crcAccum)
 7 {
 8     uint8_t tmp;
 9     tmp = data ^ (uint8_t)(*crcAccum & 0xff);
10     tmp ^= (tmp << 4);
11     *crcAccum = (*crcAccum >> 8) ^ (tmp << 8) ^ (tmp << 3) ^ (tmp >> 4);
12 }
13 inline void crc_init(uint16_t* crcAccum)
14 {
15     *crcAccum = X25_INIT_CRC;
16 }
17 inline uint16_t crc_calculate(const uint8_t* pBuffer, uint16_t length)
18 {
19     uint16_t crcTmp;
20     crc_init(&crcTmp);
21     while (length--) {
22         crc_accumulate(*pBuffer++, &crcTmp);
23     }
24     return crcTmp;
25 }
26 inline void crc_accumulate_buffer(uint16_t *crcAccum, const char *pBuffer, uint16_t length)
27 {
28     const uint8_t *p = (const uint8_t *)pBuffer;
29     while (length--) {
30         crc_accumulate(*p++, crcAccum);
31     }
32 }
33 #ifndef MAVLINK_MESSAGE_CRCS
34 #define MAVLINK_MESSAGE_CRCS {50, 124, 137, 0, 237, 217, 104, 119, 117, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 137, 214, 159, 220, 168, 24, 23, 170, 144, 67, 115, 39, 246, 185, 104, 237, 244, 222, 212, 9, 254, 230, 28, 28, 132, 221, 232, 11, 153, 41, 39, 78, 196, 132, 0, 15, 3, 0, 0, 0, 0, 0, 167, 183, 119, 191, 118, 148, 21, 0, 243, 124, 0, 0, 38, 20, 158, 152, 143, 0, 0, 14, 106, 49, 22, 143, 140, 5, 150, 0, 231, 183, 63, 54, 47, 0, 0, 0, 0, 0, 0, 175, 102, 158, 208, 56, 93, 138, 108, 32, 185, 84, 34, 174, 124, 237, 4, 76, 128, 56, 116, 134, 237, 203, 250, 87, 203, 220, 25, 226, 46, 29, 223, 85, 6, 229, 203, 1, 195, 109, 168, 181, 47, 72, 131, 127, 0, 103, 154, 178, 200, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 189, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 208, 0, 0, 0, 0, 163, 105, 151, 35, 150, 179, 0, 0, 0, 0, 0, 90, 104, 85, 95, 130, 184, 81, 8, 204, 49, 170, 44, 83, 46, 0}
35 #endif
36 static const uint8_t mavlink_message_crcs[256] = MAVLINK_MESSAGE_CRCS;
37 int main()
38 {
39     unsigned char *buff =(unsigned char*) "\xFE\x19\x3B\x01\x01\x16\x00\xA0\x8C\x45\x36\x04\x87\x01\x4D\x4E\x54\x5F\x41\x4E\x47\x4D\x41\x58\x5F\x50\x41\x4E\x00\x00\x04\xE2\xD6";
40     uint16_t checksum;
41     uint8_t ck[2];
42     checksum = crc_calculate((const uint8_t*)&buff[1], 5);
43     crc_accumulate_buffer(&checksum, (const char *)&buff[6], buff[1]);
44     crc_accumulate(mavlink_message_crcs[buff[5]], &checksum);
45     ck[0] = (uint8_t)(checksum & 0xFF);
46     ck[1] = (uint8_t)(checksum >> 8);
47     printf("%02x\n", ck[0]);
48     printf("%02x\n", ck[1]);
49     system("pause");
50     return 0;
51 }

 

posted on 2022-03-10 11:24  孤山独剑  阅读(612)  评论(0编辑  收藏  举报

导航