您的位置:首页 > 编程语言 > C语言/C++

将C语言的CRC32 代码转成JAVA的CRC32 代码

2016-01-05 11:35 399 查看
public class CustomerCRC32 {
private static long[] crc32Table = new long[256];

static {
long crcValue;
for (int i = 0; i < 256; i++) {
crcValue = i;
for (int j = 0; j < 8; j++) {
if ((crcValue & 1) == 1) {
crcValue = crcValue >> 1;
crcValue = 0x00000000edb88320L ^ crcValue;
} else {
crcValue = crcValue >> 1;

}
}
crc32Table[i] = crcValue;
}
}

public static long getCrc32(byte[] bytes) {
long resultCrcValue = 0x00000000ffffffffL;
for (int i = 0; i < bytes.length; i++) {
int index = (int) ((resultCrcValue ^ bytes[i]) & 0xff);
resultCrcValue = crc32Table[index] ^ (resultCrcValue >> 8);
}
resultCrcValue = resultCrcValue ^ 0x00000000ffffffffL;
return resultCrcValue;
}

public static void main(String[] args) {
String testStr = "{\"log\":{\"content\":\"2\",\"time\":\"2016-01-05 10:17:24\",\"type\":1001,\"version\":\"[5.0.8.12]\"},\"pcInfo\":{\"ip\":\"192.168.118.57\",\"mac\":\"94-DE-80-A8-E6-EC\",\"onlyId\":\"7CE81DDBF7D05F6AD89CD7D79FAA5905\"},\"user\":{\"name\":\"CFM\"}}";
java.util.zip.CRC32 jdkCrc32 = new java.util.zip.CRC32();
jdkCrc32.update(testStr.getBytes());
System.out.println("jdk  crc32: " + jdkCrc32.getValue());
System.out.println("test crc32: " + getCrc32(testStr.getBytes()));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: