package com.example.iot_controlhost.utils;

import com.example.iot_controlhost.model.Device;

public class DataUtils {
    //-------------------------------------------------------
    // 判断奇数或偶数，位运算，最后一位是1则为奇数，为0是偶数
    public static int isOdd(int num) {
        return num & 1;
    }

    //-------------------------------------------------------
    //Hex字符串转byte
    public static byte HexToByte(String inHex) {
        try{
            return (byte) Integer.parseInt(inHex, 16);
        } catch (Exception e) {
            return 0;
        }
    }

    //-------------------------------------------------------
    //1字节转2个Hex字符
    public static String Byte2Hex(Byte inByte) {
        return String.format("%02x", new Object[]{inByte}).toUpperCase();
    }

    //-------------------------------------------------------
    //转hex字符串转字节数组
    public static byte[] HexToByteArr(String inHex) {
        byte[] result;
        int hexlen = inHex.length();
        if (isOdd(hexlen) == 1) {
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = HexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    //字节数组转转hex字符串
    public static String ByteArrToHex(byte[] inBytArr) {
        StringBuilder strBuilder = new StringBuilder();
        for (byte valueOf : inBytArr) {
            strBuilder.append(Byte2Hex(Byte.valueOf(valueOf)));
        }
        return strBuilder.toString();
    }


    /**
     * CRC校验
     */
    public static boolean CRC16Check(String[] strings) {
        if (strings == null) {
            return false;
        }
        String str = "";
        for (int i = 0; i < strings.length - 2; i++) {
            str += strings[i];
        }
        String crc = strings[strings.length - 2] + strings[strings.length - 1];
        String crc_ = Device.getCRC(str);
        if (crc.equals(crc_)) return true;
        else return false;
    }

}
