【问题标题】:how to append unsigned short after char buffer array containing hex byte如何在包含十六进制字节的字符缓冲区数组之后附加无符号短
【发布时间】:2013-12-31 23:26:58
【问题描述】:

我正在尝试计算 2 字节的 CRC。 我有高位字节和低位字节的 CRC 值表。

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

这些在下面的函数中用于计算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) ;
}

在上述函数中,“puchMsg”是一个指向消息缓冲区的指针,其中包含 用于生成 CRC 的二进制数据,“usDataLen”是消息缓冲区中的字节数。

该函数将 CRC 作为 unsigned short 类型返回。

现在我必须在我的消息末尾附加这个 CRC 字节。

当我按以下方式发送数据时,没有 CRC

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

现在我必须计算 CRC 并将其附加到 str 的末尾,使其成为 8 个字节。

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

这里的测试将包含返回的 CRC 作为 unsigned short。如何将其作为最后 2 个字节附加到 str1[8] 中。

【问题讨论】:

    标签: c++ winapi hex byte crc


    【解决方案1】:

    这很简单,一个例子是:

    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];
    

    这取决于目标系统的字节顺序,您可以将上面的 0 与 1 交换。

    编辑:替代:

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

    【讨论】:

    • 感谢您的帮助。我想问你一个问题 unsigned 或signed char 是否影响CRC计算。
    • @user3048644 这取决于如何在 CRC16 中实现 crc 计算,在您的情况下,所有内容都被视为无符号。
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2012-06-05
    • 2021-02-03
    • 2012-02-20
    • 2014-10-07
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多