001/* 002 * BioJava development code 003 * 004 * This code may be freely distributed and modified under the 005 * terms of the GNU Lesser General Public Licence. This should 006 * be distributed with the code. If you do not have a copy, 007 * see: 008 * 009 * http://www.gnu.org/copyleft/lesser.html 010 * 011 * Copyright for this code is held jointly by the individual 012 * authors. These should be listed in @author doc comments. 013 * 014 * For more information on the BioJava project and its aims, 015 * or to join the biojava-l mailing list, visit the home page 016 * at: 017 * 018 * http://www.biojava.org/ 019 * 020 */ 021 022package org.biojavax.utils; 023 024import java.util.zip.Checksum; 025 026/** 027 * Utility class that calculates a CRC64 checksum on a stream of bytes. Code was 028 * based on some from BioPerl. Note that we use longs then cast them to avoid 029 * the lack of an unsigned int in Java. Longs are 64-bit but we are only using 030 * the bottom 32 bits. An int is 32-bit but encodes sign so we can get amusing 031 * results if we don't allow for this. 032 * 033 * @author Unknown. Copied from Expasy4J for convenience. See <a 034 * href="http://dev.isb-sib.ch/projects/expasy4j/">http://dev.isb-sib.ch/projects/expasy4j/</a> 035 * @since 1.5 036 */ 037public class CRC64Checksum implements Checksum { 038 private static final long POLY64 = 0xD800000000000000L; 039 040 private static final long[] crcTable = new long[256]; 041 042 private long crc; 043 044 static { 045 for (int i = 0; i < 256; ++i) { 046 long part = i; 047 for (int j = 0; j < 8; ++j) 048 part = ((part & 1) != 0) ? (part >>> 1) ^ POLY64 : (part >>> 1); 049 crcTable[i] = part; 050 } 051 } 052 053 public void update(int b) { 054 long low = crc >>> 8; 055 long high = crcTable[(int) ((crc ^ b) & 0xFF)]; 056 crc = low ^ high; 057 } 058 059 public void update(byte[] b, int offset, int length) { 060 for (int i = offset; i < length; ++i) 061 update(b[i]); 062 } 063 064 public void update(String s) { 065 // update(s.getBytes(), 0, s.length()); 066 int size = s.length(); 067 for (int i = 0; i < size; ++i) 068 update(s.charAt(i)); 069 070 } 071 072 public long getValue() { 073 return crc; 074 } 075 076 /** 077 * Returns a zero-padded 16 character wide string containing the current 078 * value of this checksum in uppercase hexadecimal format. 079 */ 080 public String toString() { 081 StringBuffer builder = new StringBuffer(); 082 builder.append(Long.toHexString(crc >>> 4)); 083 builder.append(Long.toHexString(crc & 0xF)); 084 for (int i = 16 - builder.length(); i > 0; --i) 085 builder.insert(0, '0'); 086 return builder.toString().toUpperCase(); 087 } 088 089 public void reset() { 090 crc = 0; 091 } 092}