Java中循环冗余校验(CRC32)的实现

CRC32简介

CRC校验实用程序库 在数据存储和数据通讯领域,为了保证数据的正确,就不得不采用检错的手段。在诸多检错手段中,CRC是最著名的一种。CRC的全称是循环冗余校验。 

CRC32检错能力极强,开销小,易于用编码器及检测电路实现。从其检错能力来看,它所不能发现的错误的几率仅为0.0047%以下。从性能上和开销上考虑,均远远优于奇偶校验及算术和校验等方式。因而,在数据存储和数据通讯领域,CRC无处不在:著名的通讯协议X.25的FCS(帧检错序列)采用的是CRC-CCITT,ARJ、LHA等压缩工具软件采用的是CRC32,磁盘驱动器的读写采用了CRC16,通用的图像存储格式GIF、TIFF等也都用CRC作为检错手段。

CRC实现

CommonUtil.getCRC32(String filePath)
/**
* 获取文件CRC32校验值
*
* @param filePath 文件绝对路径
* @return
*/
public static long getCRC32(String filePath) {
long crc32Value = 0L;
try {
CRC32 crc32 = new CRC32();
File file = FileUtil.file(filePath);
int fileLen = (int) file.length();
InputStream in = new FileInputStream(file);
//分段进行crc校验
int let = 10 * 1024 * 1024;
int sum = fileLen / let + 1;
for (int i = 0; i < sum; i++) {
if (i == sum - 1) {
let = fileLen - (let * (sum - 1));
}
byte[] b = new byte[let];
in.read(b, 0, let);
crc32.update(b);
}
crc32Value = crc32.getValue();
} catch (Exception e) {
LOGGER.error("crc32检验异常:", e);
}
return crc32Value;
}

测试代码:

@Test
public void test() {
String filePath = "C:\\Users\\admin\\Desktop\\OTA_EH-OS-M17-T01-IOT_V1.78_20200828_FV1.00.zip";
String crc32 = CommonUtil.getCRC32(filePath);
System.out.println(crc32);
}

测试结果: 

3450958763

posted @ 2020-09-26 08:52  黄进广寒  阅读(3770)  评论(0编辑  收藏  举报