我在Arduino Uno上使用代码。我一直试图让这段代码去做,就是通过我的字节数组,称为“sample”并以十六进制计算CRC-32值。我已经确认此代码成功计算CRC_32,但仅在将“sample”视为ASCII字符串时。为了更清楚地理解我的意思,请看一下: enter link description here
如果您将“sample”作为连续字符串(即82818030 .....)放在该网页上,则在选择ASCII对话框时,您将获得与HEX对话框时不同的特定答案被选中。我一直在努力实现这个结果(即0x430F8AB5)。 我将不胜感激任何帮助。
以下是代码:
#include "Arduino.h"
//#include "lib_crc.h"
unsigned char sample[90] = {
0x82,0x81, 0x80, 0x30, 0, 0, 0, 0, 0x21, 0x46, 0x01, 0x1D, 0, 0, 0, 0, 0x3F, 0x01, 0x22, 0x22, 0, 0x06, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0x80, 0x0E, 0, 0, 0, 0, 0xFA, 0, 0, 0x27, 0x85, 0x07, 0x0F, 0x4C, 0x82, 0x80, 0, 0, 0, 0x05, 0x01, 0xC1, 0x13, 0x1D, 0, 0, 0, 0, 0x3F,0x01, 0x22, 0, 0x06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0xFA, 0, 0, 0x27};
//unsigned char sample[] = "828180300000214611D00003F1222206000000000000080E0000FA0027857F4C828000051C1131D00003F122060000000000000800000FA0027";
static PROGMEM prog_uint32_t crc_table[16] = {
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
};
unsigned long crc_update(unsigned long crc, byte data)
{
byte tbl_idx;
tbl_idx = crc ^ (data >> (0 * 4));
crc = pgm_read_dword_near(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
tbl_idx = crc ^ (data >> (1 * 4));
crc = pgm_read_dword_near(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
return crc;
}
unsigned long crc_string( unsigned char*s)
{
unsigned long crc = ~0L;
while (*s)
crc = crc_update(crc, *s++);
crc = ~crc;
return crc;
}
void setup(){
Serial.begin(9600);
Serial.print(crc_string(sample),HEX);
}
void loop() // run over and over
{
}
答案 0 :(得分:1)
你的crc_string()函数正在执行:
while (*s)
crc = crc_update(crc, *s++);
将停在第一个空字节 - 我想你想循环字节数组的整个长度(这不是一个以零结尾的字符串),我猜是90字节。 即。
unsigned long crc_string( unsigned char*s, unsigned int length)
{
unsigned long crc = ~0L;
unsigned int i;
for(i=0; i<length; i++)
crc = crc_update(crc, *s++);
crc = ~crc;
return crc;
}
并致电crc_string(sample,90)
请注意,您的注释字符串828180300000214611D0...
是垃圾,因为零字节由单个“0”而不是“00”表示。