Skip to content

Commit dfe5943

Browse files
Merge pull request TheAlgorithms#130 from Pusty/master
Added crc32 implementation
2 parents 512cc9c + db7300f commit dfe5943

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Misc/crc32.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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 = Integer.reverse(crc32); //result reflect
24+
return crc32 ^ 0xFFFFFFFF; //final xor value
25+
}
26+
27+
}

0 commit comments

Comments
 (0)