16进制字符串生成CRC-16/CCITT-FALSE校验码

wuchangjian2021-11-08 19:34:46编程学习
/**
 * @author yichuan@iscas.ac.cn
 * @version 1.0
 * @date 2021/11/8 21:51
 */
public class Crc {
    /**
     * CRC-16/CCITT-FALSE x16+x12+x5+1 算法
     *
     * info
     * Name:CRC-16/CCITT-FAI
     * Width:16
     * Poly:0x1021
     * Init:0xFFFF
     * RefIn:False
     * RefOut:False
     * XorOut:0x0000
     *
     * @param hexString
     * @param
     * @return
     */
    public static String crc_16_CCITT_False(String hexString) {

        byte[] destByte = new byte[hexString.length()/2];
        int j=0;
        for(int i=0;i<destByte.length;i++) {
            byte high = (byte) (Character.digit(hexString.charAt(j), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(j + 1), 16) & 0xff);
            destByte[i] = (byte) (high << 4 | low);
            j+=2;
        }
        int crc = 0xffff; // initial value
        int polynomial = 0x1021; // poly value
        for (int index = 0; index < destByte.length; index++) {
            byte b = destByte[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }
        crc &= 0xffff;
        String strCrc = Integer.toHexString(crc).toUpperCase();
        return strCrc;
    }

    public static void main(String[] args) {
        String hexString = "043b35d468c4c534d4ea00000000008900000000000000000000edcd88962500007d000078d000f400c77c00ea000000c20001007700ba0277009a02000000000000ca1508b108ad0dad08af0dad08af08ae0fd90fe70d290a6c080808000800080808080bfd0bee0bef0f7b0f7207ff08010802080007ff08010eaf00000000000000003bab92c00a3b64c9433db2b8843c3ae4c28d3d0efdca1e3ae4c28d3d0efdca1e003c000a000c08080008080802030302020204b0390e042b0000000000000000";
        System.out.println(crc_16_CCITT_False(hexString));
    }
}

示例数据输出为1792,与网页端一致

在这里插入图片描述

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。