【发布时间】:2016-01-28 13:20:42
【问题描述】:
我将 CRC 附加到数据流中。我正在为 Linux 和 Windows 使用来自 RS-232 的串行端口库。
我想得到和comport工具图片上显示的一样的值:
我正在使用const char[4086]="123456789"; 作为缓冲区。
返回的 CRC 是 bb3d,然后我将其从 unsigned short 转换为 char *。
#define SERIALPORT_BUFSIZE 4088
char *im_buf = (char *)malloc(SERIALPORT_BUFSIZE + 8);
char *tx_buf = (char *)malloc(SERIALPORT_RCV_BUFSIZE + 8);
const char buf[SERIALPORT_BUFSIZE]="123456789";
strcpy(im_buf, buf);
WriteToSerialPort(); // call to function
void SerialPortCom::WriteToSerialPort(void)
{
if(!port_open) return;
int i,n, tmp, tmp2;
if(newline == 1)
{
strcat(im_buf, "0a");
}
else if(newline == 2)
{
strcat(im_buf, "0d");
}
else if(newline == 3)
{
strcat(im_buf, "0d0a");
}
n = strlen(im_buf) / 2;
if(n < 1) return;
for(i=0; i< n; i++)
{
tmp = im_buf[i*2];
if((tmp >= '0') && (tmp <= '9'))
{
tmp -= '0';
}
else if((tmp >= 'a') && (tmp <= 'f'))
{
tmp -= ('a' - 10);
}
else if((tmp >= 'A') && (tmp <= 'F'))
{
tmp -= ('A' - 10);
}
tmp *= 16;
tmp2 = im_buf[(i*2)+1];
if((tmp2 >= '0') && (tmp2 <= '9'))
{
tmp2 -= '0';
}
else if((tmp2 >= 'a') && (tmp2 <= 'f'))
{
tmp2 -= ('a' - 10);
}
else if((tmp2 >= 'A') && (tmp2 <= 'F'))
{
tmp2 -= ('A' - 10);
}
tmp += tmp2;
tx_buf[i] = tmp;
}
//generate crc
unsigned short crc = GetCrc16(im_buf, strlen(im_buf));
//append crc
memcpy( tx_buf + n, &crc, 2 );
//send to serial port
RS232_SendBuf(comport_nr, (unsigned char *)tx_buf, n+2);
}
我得到了什么:(12 34 56 78 70 11 4A 3D)
我想要什么:(12 34 56 78 7B 34 FD FD FD FD)
如何达到预期效果?
unsigned short SerialPortCom::GetCrc16(const char* InStr,unsigned int len)
{
//Crc16
unsigned short Crc16Table[256];
unsigned int i,j;
unsigned short Crc;
unsigned char CRCHigh = 0xFF, CRCLow = 0xFF;
for (i = 0; i < 256; i++)
{
Crc = i;
for (j = 0; j < 8; j++)
{
if(Crc & 0x1)
Crc = (Crc >> 1) ^ 0xA001;
else
Crc >>= 1;
}
Crc16Table[i] = Crc;
}
//CRC16
Crc=0x0000;
for(i=0; i<len; i++)
{
Crc = (Crc >> 8) ^ Crc16Table[(Crc & 0xFF) ^(uint8_t) InStr[i]];
}
//Crc ^= 0x0000;
return Crc;
}
【问题讨论】: