有人能帮我计算32位CRC吗?
这是我用来计算32位CRC的代码。
static unsigned int crc32_table[256];
void make_crc_table()
{
int j;
unsigned int crc,byte, mask;
/* Set up the table, if necessary. */
if (crc32_table[1] == 0)
{
for (byte = 0; byte <= 255; byte++)
{
crc = byte;
for (j = 7; j >= 0; j--) // Do eight times
{
mask = -(crc & 1);
crc = (crc >> 1) ^ (0xEDB88320 & mask);
}
crc32_table[byte] = crc;
}
}
for (j=0;j<10;j++)
printf("crc32_table[%d] = %x\n",j,crc32_table[j]);
}
unsigned int crc32cx(unsigned int crc,unsigned char *message,int len)
{
unsigned int word;
do
{
if((word = *(unsigned int *)message) & 0xFF)
{
crc = crc ^ word;
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
message = message + 4;
len--;
}
}while(len == 0);
return ~crc;
}
main()
{
unsigned int crc = 0xFFFFFFFF;
unsigned char buff[100] = ABCDEFGH;
int len; // lenght in bytes
len = (((strlen(buff)%8)==0) ? (strlen(buff)/8) : ((strlen(buff)/8)+1));
printf("lenght in bytes %d\n",len);
make_crc_table();
printf("crc = %x\n",crc32cx(crc,buff,len));
}有人能帮我解释一下为什么这与在线32位CRC计算器不匹配吗?链接如下
http://www.tahapaksu.com/crc/
对于输入buff=12345678,我的CRC正在与在线的CRC进行匹配。对于其他值,如buff = ABCD1234,输出不匹配。
谢谢。
发布于 2016-02-11 10:40:01
这里的问题是代码的编写方式;让我解释一下:
unsigned int crc32cx(unsigned int crc,unsigned char *message,int len)
{
unsigned int word;
do
{
if((word = *(unsigned int *)message) & 0xFF)
{
crc = crc ^ word;
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
message = message + 4;
len--;
}
}while(len == 0);
return ~crc;
}这个函数所做的是一次读取4个字符并计算CRC (XOR操作);维基百科解释了它背后的数学。但是你要做这个操作len倍
unsigned char buff[100] = ABCDEFGH;
int len; // lenght in bytes
printf("crc = %x\n",crc32cx(crc,buff,4));因此,在您的示例中,您将读取4x4字节;您的缓冲区将包含:
buff = ['A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' '\n' 'trash' 'trash'.... ]您有8个字节的信息,后面是'\n‘,因为您为缓冲区分配了一个字符串,而不是回收站,因为缓冲区是在堆栈上分配的。你读的是16个字节。我相信你现在已经能发现问题了,但以防万一,我认为crc32cx(crc,buff,2)应该能解决你的问题。
发布于 2016-02-11 13:32:12
您的CRC代码非常不标准。在执行表方法时,您应该逐字节输入数据,而不是逐块输入数据,这肯定会导致一些输入和逻辑问题。最大的一条是这行if(word = *(unsigned int *)message) & 0xFF),它完全没有必要,在某些情况下将忽略有效的传入数据。
一个好的、简单的、干净的crc32 C实现可以是在这里看到的。看看它和你的,并做了一些调整,它是有效的。
在您的函数中,您可以将循环和变量更改为:
unsigned char word;
do
{
word = *message;
crc = crc ^ word;
crc = (crc >> 8) ^ crc32_table[crc & 0xFF];
message++;
len--;
}while(len > 0);现在,在主目录中,您可以使用len = strlen(buff)找到输入数据的长度。
https://stackoverflow.com/questions/35334578
复制相似问题