JAVA CRC-CCITT (Kermit)!!内网仅此一份

本文详细介绍了CRC-CCITT(Kermit)校验算法的实现过程,提供了一个从C语言翻译过来的Java版本实现。通过初始化生成多项式表,更新CRC值,最终返回经过字节交换的CRC校验结果。文中包含完整的Java代码示例,展示了如何计算字符串和字节数组的CRC值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近碰到个 CRC-CCITT (Kermit)校验算法,于是我百度一顿操作,毫无结果。没找到任何JAVA版本的 CRC-CCITT (Kermit),其他的语言也少!终于在一个神奇的地方找到了一个C语言版本,翻译过来如下,特此分享!

C版本原址:http://www.lammertbies.nl/comm/info/crc-calculation.html 

public class Crc {
    private static final int POLYNOMIAL = 0x8408;
    private static final int PRESET = 0;
    static private int[] tab;

    static {
        tab = new int[256];
        for (int i = 0; i < 256; i++) {
            tab[i] = initial((byte) i);
        }
    }

    private static int initial(byte c) {
        int crc = 0;
        for (int j = 0; j < 8; j++) {
            if (((crc ^ c) & 1) == 1) {
                crc = ((crc >> 1) ^ POLYNOMIAL);
            } else {
                crc = (crc >> 1);
            }
            c = (byte) (c >> 1);
        }
        return crc;
    }

    private static int update_crc(int crc, byte c) {
        int cc = (0xff & c);

        int tmp = (crc ^ cc);
        crc = (crc >> 8) ^ tab[tmp & 0xff];

        return crc;
    }

    private static int swab(int n) {
        return (((n & 0xFF00) >> 8) + ((n & 0xFF) << 8));
    }

    public static int crc(String str) {
        return crcb(str.getBytes());
    }

    public static int crcb(byte... i) {
        int crc = PRESET;
        for (byte c : i) {
            crc = update_crc(crc, c);
        }
        return swab(crc);
    }

    public static void main(String[] args) {
        int crc = Crc.crcb((byte) 0xFC, (byte) 5, (byte) 0x11);
        System.out.println(Integer.toHexString(crc));
        crc = Crc.crc("123456789");//结果是0x8921
        System.out.println(Integer.toHexString(crc));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值