package com.zksy.manhole.utils;

/**
 * @Description
 * @Date 2025- 03-06-上午 9:02
 * @auther tuDouSi
 */
public class DataCheckUtil {
    /**
     *
     * @description: crc16校验,输入一个数据,返回一个数组.
     * @param str
     * @return 返回两个校验码,低字节在前,高字节在后
     *
     */
    public static String crc16(String str) {
        int[] data = hexStringToIntArray(str);
        int xda, xdapoly;
        int i, j, xdabit;
        xda = 0xFFFF;
        xdapoly = 0xA001;
        for (i = 0; i < data.length; i++) {
            xda ^= data[i];
            for (j = 0; j < 8; j++) {
                xdabit = (int) (xda & 0x01);
                xda >>= 1;
                if (xdabit == 1) {
                    xda ^= xdapoly;
                }
            }
        }
        byte[] temdata = new byte[2];
        temdata[0] = (byte) (xda & 0xFF);
        temdata[1] = (byte) (xda >> 8);
        return bytesToHexString(temdata);
    }
    // 将十六进制字符串转换为整数数组
    private static int[] hexStringToIntArray(String str) {
        if (str.length() % 2 != 0) {
            throw new IllegalArgumentException("Hex string length must be even");
        }

        int[] result = new int[str.length() / 2];
        for (int i = 0; i < str.length(); i += 2) {
            result[i / 2] = Integer.parseInt(str.substring(i, i + 2), 16);
        }
        return result;
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}
