简体   繁体   English

如何在包含十六进制字节的char缓冲区数组后附加无符号的short

[英]how to append unsigned short after char buffer array containing hex byte

I am trying to calculate CRC of 2 byte. 我正在尝试计算2字节的CRC。 I have Table of CRC values for high–order byte and low–order byte. 我有高阶字节和低阶字节的CRC值表。

static unsigned char auchCRCHi[] = {0x00, 0xC1, 0x81, 0x40, 0x01............0x40} ;
static char auchCRCLo[] = {0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03....0x40} ;

These are used in below function to calculate CRC. 这些在以下功能中用于计算CRC。

unsigned short CRC16(unsigned char* puchMsg, unsigned short usDataLen)
{
    unsigned char uchCRCHi = 0xFF ; /* high byte of CRC initialized */
    unsigned char uchCRCLo = 0xFF ; /* low byte of CRC initialized */
    unsigned uIndex ; /* will index into CRC lookup table */

    while (usDataLen--) /* pass through message buffer */
    {
        uIndex = uchCRCHi ^ *puchMsg++ ; /* calculate the CRC */
        uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex] ;
        uchCRCLo = auchCRCLo[uIndex] ;
     }

     return (uchCRCHi << 8 | uchCRCLo) ;
}

In the above function "puchMsg" is A pointer to the message buffer containing binary data to be used for generating the CRC and "usDataLen" is the quantity of bytes in the message buffer. 在上面的函数中,“ puchMsg”是指向消息缓冲区的指针,该消息缓冲区包含用于生成CRC的二进制数据,而“ usDataLen”是消息缓冲区中的字节数。

The function returns the CRC as a type unsigned short. 该函数以无符号short类型返回CRC。

Now I have to append this CRC byte at the end of my message. 现在,我必须在消息末尾附加此CRC字节。

Without CRC when i send my data in the following way it works 当我以以下方式发送数据时没有CRC

char str[6]={0x01,0x01,0x00,0x01,0x00,0x20};// sending hex of $$S??
serialObj.send(str, 6);

Now I have to calculate the CRC and append it at the end of str making it 8 byte. 现在,我必须计算CRC并将其附加在str的末尾,使其成为8个字节。

unsigned char str1[8] ={0x01,0x01,0x00,0x01,0x00, 0x20};
unsigned char* str2 = str1;
unsigned short test;
test= CRC16(str1,8);

here test will contain the returned CRC as unsigned short. 在这里,测试将包含返回的CRC(无符号短)。 How to append it as last 2 byte in str1[8]. 如何将其追加为str1 [8]的最后2个字节。

It's pretty simple, one example would be: 这很简单,一个例子是:

unsigned char buffer[8] ={0x01, 0x01, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00};
unsigned short crc = CRC16(buffer, 8); // Calculates the CRC16 of all 8 bytes
buffer[6] = ((char*) &crc)[0];
buffer[7] = ((char*) &crc)[1];

It depends on the byte order of the destination system, you may swap 0 with 1 above. 这取决于目标系统的字节顺序,您可以将0与上面的1交换。

Edit: Alternative: 编辑:替代:

*((unsigned short*) &buffer[6]) = crc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM