2019-05-09 19:32:54 +08:00
|
|
|
package Others;
|
|
|
|
|
2017-10-03 09:57:28 +08:00
|
|
|
import java.util.BitSet;
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/** Generates a crc32 checksum for a given string or byte array */
|
2019-02-17 20:52:00 +08:00
|
|
|
public class CRC32 {
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
public static void main(String[] args) {
|
|
|
|
System.out.println(Integer.toHexString(crc32("Hello World")));
|
|
|
|
}
|
2019-02-17 20:52:00 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
public static int crc32(String str) {
|
|
|
|
return crc32(str.getBytes());
|
|
|
|
}
|
2019-02-17 20:52:00 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
public static int crc32(byte[] data) {
|
|
|
|
BitSet bitSet = BitSet.valueOf(data);
|
|
|
|
int crc32 = 0xFFFFFFFF; // initial value
|
|
|
|
for (int i = 0; i < data.length * 8; i++) {
|
|
|
|
if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0))
|
|
|
|
crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial
|
|
|
|
else crc32 = (crc32 << 1);
|
2017-10-03 09:57:28 +08:00
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
crc32 = Integer.reverse(crc32); // result reflect
|
|
|
|
return crc32 ^ 0xFFFFFFFF; // final xor value
|
|
|
|
}
|
2017-10-03 09:57:28 +08:00
|
|
|
}
|