CrcUtil.java 1.42 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package com.zehong.gassdevicereport.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class CrcUtil {

    /**
     * 计算CRC16校验码
     * @param bytes
     * @return
     */
    public static int getCRC(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return CRC;
    }

    public static String getCrcToHex(byte[] bytes) {
        return Integer.toHexString(getCRC(bytes));
    }

    /**
     * 计算CRC16校验码
     * @param bytes
     * @param reverse 是否转换高低位
     * @return
     */
耿迪迪's avatar
耿迪迪 committed
42
    public static String getCrcToHex(byte[] bytes,boolean reverse) {
43 44 45
        int CRC = getCRC(bytes);
        //高低位转换,看情况使用(譬如本人这次对led彩屏的通讯开发就规定校验码高位在前低位在后,也就不需要转换高低位)
        if(reverse){
46
            //高低位互换,输出符合相关工具对Modbus CRC16的运算
47 48
            CRC = ( (CRC & 0x0000FF00) >> 8) | ( (CRC & 0x000000FF ) << 8);
        }
49
        return String.format("%04x", CRC);
50 51 52 53 54
    }
}