CRC16算法Java实现

模仿C++代码改写的Java实现

 

public class CRC16 {
    private short[] crcTable = new short[256];
    private int gPloy = 0x1021; // 生成多项式

    public CRC16() {
        computeCrcTable();
    }

    private short getCrcOfByte(int aByte) {
        int value = aByte << 8;

        for (int count = 7; count >= 0; count--) {
            if ((value & 0x8000) != 0) { // 高第16位为1,可以按位异或
                value = (value << 1) ^ gPloy;
            } else {
                value = value << 1; // 首位为0,左移
            }

        }
        value = value & 0xFFFF; // 取低16位的值
        return (short)value;
    }

    /*
     * 生成0 - 255对应的CRC16校验码
     */
    private void computeCrcTable() {
        for (int i = 0; i < 256; i++) {
            crcTable[i] = getCrcOfByte(i);
        }
    }

    public short getCrc(byte[] data) {
        int crc = 0;
        int length = data.length;
        for (int i = 0; i < length; i++) {
            crc = ((crc & 0xFF) << 8) ^ crcTable[(((crc & 0xFF00) >> 8) ^ data[i]) & 0xFF];
        }
        crc = crc & 0xFFFF;
        return (short)crc;
    }
}

 

public final class CodecUtil {
    static CRC16 crc16 = new CRC16();

    private CodecUtil() {
    }

    public static byte[] short2bytes(short s) {
        byte[] bytes = new byte[2];
        for (int i = 1; i >= 0; i--) {
            bytes[i] = (byte)(s % 256);
            s >>= 8;
        }
        return bytes;
    }

    public static short bytes2short(byte[] bytes) {
        short s = (short)(bytes[1] & 0xFF);
        s |= (bytes[0] << 8) & 0xFF00;
        return s;
    }

    /*
     * 获取crc校验的byte形式
     */
    public static byte[] crc16Bytes(byte[] data) {
        return short2bytes(crc16Short(data));
    }

    /*
     * 获取crc校验的short形式
     */
    public static short crc16Short(byte[] data) {
        return crc16.getCrc(data);
    }

    public static void main(String[] args) {
        byte[] test = new byte[] {0, 1, 2, 3, 4};
        byte[] crc = crc16Bytes(test);

        byte[] testc = new byte[test.length + 2];
        for (int i = 0; i < test.length; i++) {
            testc[i] = test[i];
        }
        testc[test.length] = crc[0];
        testc[test.length + 1] = crc[1];

        System.out.println(crc16Short(testc));
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值