CRC32
今天在看rocketmq源码时,看到CRC32,就记录下来以供学习。主要用途:
在远距离数据通信中,为确保高效而无差错地传送数据,必须对数据进行校验即差错控制。循环冗余校验CRC(Cyclic Redundancy Check/Code)是对一个传送数据块进行校验,是一种高效的差错控制方法。
if (!checksum(ctx, request, requestHeader)) {
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("crc32 not match");
return response;
}
private boolean checksum(ChannelHandlerContext ctx, RemotingCommand request,
RegisterBrokerRequestHeader requestHeader) {
if (requestHeader.getBodyCrc32() != 0) {
final int crc32 = UtilAll.crc32(request.getBody());
if (crc32 != requestHeader.getBodyCrc32()) {
log.warn(String.format("receive registerBroker request,crc32 not match,from %s",
RemotingHelper.parseChannelRemoteAddr(ctx.channel())));
return false;
}
}
return true;
}
public static int crc32(byte[] array) {
if (array != null) {
return crc32(array, 0, array.length);
}
return 0;
}
public static int crc32(byte[] array, int offset, int length) {
CRC32 crc32 = new CRC32();
crc32.update(array, offset, length);
return (int) (crc32.getValue() & 0x7FFFFFFF);
}