Java by API/java.util.zip/Checksum
Содержание
Checksum: getValue()
<source lang="java">
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.CRC32; import java.util.zip.Checksum; public class Main {
public static void main(String[] args) throws IOException { FileInputStream fin = new FileInputStream(args[0]); System.out.println(args[0] + ":\t" + getCRC32(fin)); fin.close(); } public static long getCRC32(InputStream in) throws IOException { Checksum cs = new CRC32(); for (int b = in.read(); b != -1; b = in.read()) { cs.update(b); } return cs.getValue(); }
}
</source>
Checksum: reset()
<source lang="java">
import java.util.zip.CRC32; import java.util.zip.Checksum; public class Main {
public static void main(String[] argv) throws Exception { byte[] bytes = "some data".getBytes(); // Compute Adler-32 checksum Checksum checksumEngine = new CRC32(); checksumEngine.update(bytes, 0, bytes.length); long checksum = checksumEngine.getValue(); checksumEngine.reset(); }
}
</source>
Checksum: update(int b)
<source lang="java">
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.CRC32; import java.util.zip.Checksum; public class Main {
public static void main(String[] args) throws IOException { FileInputStream fin = new FileInputStream(args[0]); System.out.println(args[0] + ":\t" + getCRC32(fin)); fin.close(); } public static long getCRC32(InputStream in) throws IOException { Checksum cs = new CRC32(); for (int b = in.read(); b != -1; b = in.read()) { cs.update(b); } return cs.getValue(); }
}
</source>
implements Checksum
<source lang="java">
import java.util.zip.Checksum; public class ParityChecksum implements Checksum {
long checksum = 0; public void update(int b) { int numOneBits = 0; for (int i = 1; i < 256; i *= 2) { if ((b & i) != 0) numOneBits++; } checksum = (checksum + numOneBits) % 2; } public void update(byte data[], int offset, int length) { for (int i = offset; i < offset + length; i++) { this.update(data[i]); } } public long getValue() { return checksum; } public void reset() { checksum = 0; }
}
</source>