CRC-16/IBM JAVA 模2取余

public class CRC16 {
    private static final int POLY = 0x8005;
    private static final int INIT = 0x0000;
    private static final int XOROUT = 0x0000;

    /**
     *
     * @param data 反转前数据
     * @return
     */
    public static int crc16(int[] data) {
        // 数据反转
        batchDataReverse(data, 8);

        int crc = INIT;
        for (int b : data) {
            crc ^= (b & 0xFF) << 8;
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x8000) != 0) {
                    crc = (crc << 1) ^ POLY;
                } else {
                    crc <<= 1;
                }
            }
        }


        return dataReverse(crc & 0xFFFF ^ XOROUT, 16);
    }

    /**
     *
     * 批量反转
     * @param data 待反转数据
     */
    private static void  batchDataReverse(int[] data, int byteLength) {
        for (int i = 0; i < data.length; i++) {
            data[i] =  dataReverse(data[i], byteLength);
        }
    }

    /**
     *
     * @param data
     * @param byteLength 字节长度
     * @return
     */
    private static int dataReverse(int data, int byteLength) {
        final String string = StringUtils.leftPad(Integer.toBinaryString(data), byteLength, "0");
        final String reverse = StringUtils.reverse(string);
        return Integer.parseInt(reverse, 2);
    }

    public static String strComputeCRC16(String strData){
        // 字符串转int类型
        final int[] ints1 = StringUtils.toCodePoints(strData);
        int crc1 = crc16(ints1);
        return StringUtils.leftPad(Integer.toHexString(crc1).toUpperCase(), 4, "0");
    }

    public static void main(String[] args) {

        String str = "123";
        final String s = strComputeCRC16(str);

       

    }

}

所得结果与 CRC(循环冗余校验)在线计算_ip33.com CRC-16/IBM结果一致

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值