Skip to content

Commit f2bfa6a

Browse files
authored
crc32 implementation
1 parent 7df4e98 commit f2bfa6a

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Misc/crc32.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.BitSet;
2+
3+
//Generates a crc32 checksum for a given string or byte array
4+
public class crc32 {
5+
6+
public static void main(String[] args) {
7+
System.out.println(Integer.toHexString(crc32("Hello World")));
8+
}
9+
10+
public static int crc32(String str) {
11+
return crc32(str.getBytes());
12+
}
13+
14+
public static int crc32(byte[] data) {
15+
BitSet bitSet = BitSet.valueOf(data);
16+
int crc32 = 0xFFFFFFFF; //initial value
17+
for(int i=0;i<data.length*8;i++) {
18+
if(((crc32>>>31)&1) != (bitSet.get(i)?1:0))
19+
crc32 = (crc32 << 1) ^ 0x04C11DB7; //xoring with polynomial
20+
else
21+
crc32 = (crc32 << 1);
22+
}
23+
crc32 = crc32 ^ 0;
24+
crc32 = Integer.reverse(crc32); //result reflect
25+
return crc32 ^ 0xFFFFFFFF; //final xor value
26+
}
27+
28+
}

0 commit comments

Comments
 (0)