/
FindChecksumOfChecksum.java
executable file
·80 lines (67 loc) · 2.36 KB
/
FindChecksumOfChecksum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package net.orfjackal.experimental;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.CRC32;
/**
* Inspired by http://stackoverflow.com/questions/2554143/how-to-find-a-checksum-of-the-same-checksum-job-interview-question
*
* @author Esko Luontola
* @since 31.3.2010
*/
public class FindChecksumOfChecksum {
static final Charset ASCII = Charset.forName("US-ASCII");
public static void main(String[] args) {
System.out.println("Start on " + new Date());
for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
if (i % (Integer.MAX_VALUE / 128) == 0) {
System.out.println("Calculating... " + i);
}
checkChecksumOfChecksum((int) i);
}
System.out.println("End on " + new Date());
}
private static void checkChecksumOfChecksum(int checksum) {
String hex = toLowercaseHex32(checksum);
byte[] lowercase = hex.getBytes(ASCII);
byte[] uppercase = hex.toUpperCase().getBytes(ASCII);
byte[] bigEndian = intToBytesBigEndian(checksum);
byte[] littleEndian = intToBytesLittleEndian(checksum);
checkChecksum(checksum, lowercase);
checkChecksum(checksum, uppercase);
checkChecksum(checksum, bigEndian);
checkChecksum(checksum, littleEndian);
}
static String toLowercaseHex32(int checksum) {
String hex = Integer.toHexString(checksum);
while (hex.length() < 8) {
hex = "0" + hex;
}
return hex;
}
static byte[] intToBytesBigEndian(int value) {
return new byte[]{
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value,
};
}
static byte[] intToBytesLittleEndian(int value) {
return new byte[]{
(byte) value,
(byte) (value >>> 8),
(byte) (value >>> 16),
(byte) (value >>> 24),
};
}
private static void checkChecksum(int expected, byte[] bytes) {
if (getCrc32(bytes) == expected) {
System.out.println("FOUND! " + toLowercaseHex32(expected) + " " + Arrays.toString(bytes));
}
}
static int getCrc32(byte[] bytes) {
CRC32 crc = new CRC32();
crc.update(bytes);
return (int) crc.getValue();
}
}