package com.zksy.environmentHJ212.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * @Description
 * @Date 2021- 06-04-上午 9:02
 * @auther Javen
 */
public class DataCheckUtil {
    /**
     * 进行CRC16数据传输协议校验
     * @param puchMsg
     * @param usDataLen
     * @return
     */
    public static String crc16_Checkout(String puchMsg, int usDataLen){
        try {
            int i,j,crc_reg,check;

            crc_reg=0xFFFF;
            char[] chars = puchMsg.toCharArray();
            for(i=0;i<usDataLen;i++){
                crc_reg=(crc_reg>>8)^chars[i];
                for(j=0;j<8;j++) {
                    check = crc_reg&0x0001;
                    crc_reg>>=1;
                    if(check==0x0001) {
                        crc_reg^=0xA001;
                    }
                }
            }
            String code = as10to16(crc_reg);
            return code;
        }catch (Exception e){
            e.printStackTrace();
        }
        return puchMsg;
    }

    /**
     * 将10进制转16进制
     * @param number
     * @return
     */
    public static String as10to16(int number) {
        int i = 0;
        StringBuffer dataCode = new StringBuffer();
        char[] crc16Char = new char[100];
        if(number == 0){
            System.out.print(0);
        } else {
            while(number!=0) {
                int t=number%16;
                if(t >=0 && t<10) {
                    crc16Char[i] = (char)(t+'0');
                    i++;
                } else {
                    crc16Char[i] = (char)(t+'A'-10);
                    i++;
                }
                number=number/16;
            }

            for (int j=i-1;j>=0;j--) {
                dataCode.append(crc16Char[j]);
            }
        }
        //长度补齐4位
        String paddedString = StringUtils.leftPad(String.valueOf(dataCode), 4, '0');
        return paddedString;
    }
}
