CRC32校验算法

public class CRC32
{
/** The crc data checksum so far. */
private uint crc = 0;

    /** The fast CRC table. Computed once when the CRC32 class is loaded. */
    private static uint[] crcTable = makeCrcTable();

    /** Make the table for a fast CRC. */
    private static uint[] makeCrcTable() {
        uint[] crcTable = new uint[256];
        for (int n = 0; n < 256; n++) {
            uint c = (uint)n;
            for (int k = 8; --k >= 0; ) {
                if((c & 1) != 0) c = 0xedb88320 ^ (c >> 1);
                else c = c >> 1;
            }
            crcTable[n] = c;
        }
        return crcTable;
    }

    /**
     * Returns the CRC32 data checksum computed so far.
     */
    public uint getValue() {
        return crc & 0xffffffff;
    }

    /**
     * Resets the CRC32 data checksum as if no update was ever called.
     */
    public void reset() {
        crc = 0;
    }

    /**
     * Adds the complete byte array to the data checksum.
     * 
     * @param buf the buffer which contains the data
     */
    public void update(byte[] buf) {
        uint off = 0;
        int len = buf.Length;
        uint c = ~crc;
        while(--len >= 0) c = crcTable[(c ^ buf[off++]) & 0xff] ^ (c >> 8);
        crc = ~c;
    }

    /**
     * Adds the complete byte array to the data checksum.
     * 
     * @param buf the buffer which contains the data
     */
    public void update(byte[] buf, int off, int len)
    {
        uint c = ~crc;
        while (--len >= 0) c = crcTable[(c ^ buf[off++]) & 0xff] ^ (c >> 8);
        crc = ~c;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,424评论 0 10
  • 高三时,我班的学霸跟班主任闹翻了,原因只是因为学霸说了班主任的目标是欲望。当时班主任特别的生气,骂的很大声,气氛也...
    浅浅的笺阅读 495评论 2 2
  • 5v5 团战 完胜 我给自己说打完这一架 军校生活也算是完美了 以前对完美军旅生涯的定义是 既立过功又背过处分还关...
    一身橄榄绿阅读 377评论 2 3
  • 跟着曹师学中医 契要:此篇之由来,吾思之良久,终提笔疾⻜。 翻开往⽇⽼师授课(《中医药学是打开中华⽂明宝库的钥匙》...
    少一先生阅读 677评论 0 0