Java Reference
In-Depth Information
Table 9-1. Computing the Adler-32 checksum for the String HELLO
Character
ASCII Value (Base 10)
A
B
H
72
1 + 72 = 73
0 + 73 = 73
E
69
73 + 69 = 142
73 + 142 = 215
L
76
142 + 76 = 218
215 + 218 = 433
L
76
218 + 76 = 294
433 + 294 = 727
O
79
294 + 79 = 373
727 + 373 = 1100
C = B * 65536 + A
= 1100 * 65536 + 373
= 72089973
Java provides an Adler32 class in the java.util.zip package to compute the Adler-32 checksum for bytes of
data. You need to call the update() method of this class to pass bytes to it. Once you have passed all bytes to it, call its
getValue() method to get the checksum. CRC32 ( C yclic R edundancy C heck 32-bit) is another algorithm to compute a
32-bit checksum. There is also another class named CRC32 in the same package, which lets you compute a checksum
using the CRC32 algorithm. Listing 9-1 illustrates how to use the Adler32 and CRC32 classes to compute checksums.
Listing 9-1. Computing Adler32 and CRC32 Checksums
// ChecksumTest.java
package com.jdojo.archives;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
public class ChecksumTest {
public static void main(String[] args) throws Exception {
String str = "HELLO";
byte[] data = str.getBytes("UTF-8");
System.out.println("Adler32 and CRC32 checksums for " + str);
// Compute Adler32 checksum
Adler32 ad = new Adler32();
ad.update(data);
long adler32Checksum = ad.getValue();
System.out.println("Adler32: " + adler32Checksum);
// Compute CRC32 checksum
CRC32 crc = new CRC32();
crc.update(data);
long crc32Checksum = crc.getValue();
System.out.println("CRC32: " + crc32Checksum);
}
}
 
Search WWH ::




Custom Search