View Javadoc

1   // CRC32.java, created Mon Jul  8 14:17:23 2002 by joewhaley
2   // Copyright (C) 2001-3 John Whaley <jwhaley@alum.mit.edu>
3   // Licensed under the terms of the GNU LGPL; see COPYING for details.
4   package joeq.ClassLib.Common.java.util.zip;
5   
6   import java.util.zip.Checksum;
7   
8   /***
9    * CRC32
10   *
11   * @author  John Whaley <jwhaley@alum.mit.edu>
12   * @version $Id: CRC32.java 1451 2004-03-09 06:27:08Z jwhaley $
13   */
14  public abstract class CRC32 implements Checksum {
15  
16    /*** The crc data checksum so far. */
17    private int crc = 0;
18  
19    /*** The fast CRC table. Computed once when the CRC32 class is loaded. */
20    private static int[] crc_table = make_crc_table();
21  
22    /*** Make the table for a fast CRC. */
23    private static int[] make_crc_table ()
24    {
25      int[] crc_table = new int[256];
26      for (int n = 0; n < 256; n++)
27        {
28          int c = n;
29          for (int k = 8;  --k >= 0; )
30            {
31              if ((c & 1) != 0)
32                c = 0xedb88320 ^ (c >>> 1);
33              else
34                c = c >>> 1;
35            }
36          crc_table[n] = c;
37        }
38      return crc_table;
39    }
40  
41    /***
42     * Returns the CRC32 data checksum computed so far.
43     */
44    public long getValue ()
45    {
46      return (long) crc & 0xffffffffL;
47    }
48  
49    /***
50     * Resets the CRC32 data checksum as if no update was ever called.
51     */
52    public void reset () { crc = 0; }
53  
54    /***
55     * Updates the checksum with the int bval. 
56     *
57     * @param bval (the byte is taken as the lower 8 bits of bval)
58     */
59  
60    public void update (int bval)
61    {
62      int c = ~crc;
63      c = crc_table[(c ^ bval) & 0xff] ^ (c >>> 8);
64      crc = ~c;
65    }
66  
67    /***
68     * Adds the byte array to the data checksum.
69     *
70     * @param buf the buffer which contains the data
71     * @param off the offset in the buffer where the data starts
72     * @param len the length of the data
73     */
74    public void update (byte[] buf, int off, int len)
75    {
76      int c = ~crc;
77      while (--len >= 0)
78        c = crc_table[(c ^ buf[off++]) & 0xff] ^ (c >>> 8);
79      crc = ~c;
80    }
81  
82    /***
83     * Adds the complete byte array to the data checksum.
84     */
85    public void update (byte[] buf) { update(buf, 0, buf.length); }
86  }