3个版本
0.1.3 | 2023年5月24日 |
---|---|
0.1.2 |
|
0.1.1 | 2021年3月30日 |
0.1.0 | 2021年3月30日 |
在算法中排名1126
在2个crate中使用(通过symcode)
24KB
566 行
CRC Zoo
此crate提供一组循环冗余校验(CRC)算法,包括CRC5、CRC8、CRC16和CRC32。
实现使用https://pycrc.org/生成,使用位操作算法,不使用查找表,最适合检查少量数据。
该Zoo收集自https://crccalc.com/并已验证。
CRC5
crc5()
CRC8
crc8()
crc8_cdma2000()
crc8_darc()
crc8_dvb_s2()
crc8_ebu()
crc8_i_code()
crc8_itu()
crc8_maxim()
crc8_rohc()
crc8_wcdma()
CRC16
crc16_ccitt_false()
crc16_arc()
crc16_aug_ccitt()
crc16_buypass()
crc16_cdma2000()
crc16_dds_110()
crc16_dect_r()
crc16_dect_x()
crc16_dnp()
crc16_en_13757()
crc16_genibus()
crc16_maxim()
crc16_mcrf4xx()
crc16_riello()
crc16_t10_dif()
crc16_teledisk()
crc16_tms37157()
crc16_usb()
crc16_a()
crc16_kermit()
crc16_modbus()
crc16_x_25()
crc16_xmodem()
CRC32
crc32()
crc32_bzip2()
crc32c()
crc32d()
crc32_mpeg2()
crc32_posix()
crc32q()
crc32_jamcrc()
crc32_xfer()
用法
调用预定义函数
use crczoo::{crc8, calculate_crc8};
assert_eq!(crc8(&"123456789".to_owned().into_bytes()), 0xF4);
指定多项式参数
pub fn calculate_crc8(data: &[u8], poly: u8, init: u8, ref_in: bool, ref_out: bool, xor_out: u8) -> u8;
assert_eq!(calculate_crc8(&"123456789".to_owned().into_bytes(), 0x07, 0x00, false, false, 0x00), 0xF4);
CRC解释
使用CRC检测字节流中错误的示例
use crczoo::crc8;
// first this is the data to protect
let mut data = "123456789".to_owned().into_bytes();
// here we obtain the checksum
let checksum = crc8(&data);
data.push(checksum);
// with the checksum appended to the original byte stream, the CRC should yield 0
assert_eq!(crc8(&data), 0);
// now let's introduce 1 bit error: i.e. '0' = 0x30, '1' = 0x31
let mut data = "023456789".to_owned().into_bytes();
data.push(checksum);
// non zero value means there is error!
assert!(crc8(&data) != 0);
// rinse and repeat, introduce 2 bits error this time
let mut data = "023456799".to_owned().into_bytes();
data.push(checksum);
// non zero value means there is error!
assert!(crc8(&data) != 0);
如https://users.ece.cmu.edu/~koopman/crc/中所述,不同的多项式有不同的错误检测能力。通常,一个好的CRC应该能够检测字节流中长度不超过一定值的所有1位和2位错误,然后随着更多位翻转和字节流变长,错误检测能力会下降。
CRC参数化解释
来自http://www.sunshine2k.de/articles/coding/crc/understanding_crc.html#ch7
以下标准参数用于定义CRC算法实例
名称:在文献中使用的名称,例如CRC-8/CDMA2000,CRC-16/CCITT。
宽度(以位为单位):定义CRC值的宽度(n位)。同时,也定义了生成多项式的宽度(n+1位)。最常用的宽度是8位、16位和32位。在实践中,甚至可以使用相当大的(80位)或非均匀的(5位或31位)宽度。
多项式:用于生成多项式的值。有不同方式用十六进制表示生成多项式,但最常见的是丢弃最高位,因为它始终为1。
初始值:用于初始化CRC值的值。
输入反射:如果此值为TRUE,则在计算之前将每个输入字节进行反射。反射意味着使用输入字节的位顺序相反。因此,这意味着位0被视为最高位,位7被视为最低位。
示例:字节0x82 = b10000010:反射(0x82) = 反射(b10000010) = b01000001 = 0x41。
结果反映:如果此值是TRUE,则最终CRC值在返回之前会被反映。反映操作在整个CRC值上执行,例如,CRC-32值会在所有32位上被反映。
最终XOR值:在返回之前,最终XOR值会与最终CRC值进行异或操作。这是在“结果反映”步骤之后进行的。显然,最终XOR值为0没有影响。
校验值(可选):此值不是必需的,但通常指定以帮助验证实现。这是输入字符串“123456789”的CRC值,或者作为字节数组:[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]。