package com.chinaitop.depot.intelligent.utils;

/**
 * @author qingsong.han
 * @description: 十六进制转换
 * @create 2019-01-15 19:04
 */
@SuppressWarnings("all")
public class HexConvertUtils {

    /**
     * 大写字符数组
     */
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 字符串转换成为16进制
     * @param str
     * @return
     */
    public static String strConvertHex(String str) {
        str = str.toUpperCase();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(DIGITS_UPPER[bit]);
            bit = bs[i] & 0x0f;
            sb.append(DIGITS_UPPER[bit]);
        }
        return sb.toString().trim();
    }

    /**
     * 把16进制字符串转换成字节数组
     * @param
     * @return byte[]
     */
    public static byte[] hexStringToByte(String hex) {
        hex = hex.toUpperCase();
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }
    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    /**
     * 字节数组转成16进制表示格式的字符串
     *
     * @param byteArray
     *            需要转换的字节数组
     * @return 16进制表示格式的字符串
     **/
    public static String toHexString(byte[] byteArray) {
        if (byteArray == null || byteArray.length < 1)
            throw new IllegalArgumentException("this byteArray must not be null or empty");

        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零
                hexString.append("0");
            hexString.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return hexString.toString().toUpperCase();
    }

    /**
     * 将10进制转换成16进制
     * @param n
     * @return
     */
    public static String decToHex(int n) {
        StringBuffer s = new StringBuffer();
        while(n != 0){
            s = s.append(DIGITS_UPPER[n%16]);
            n /= 16;
        }
        return s.reverse().toString();
    }

}
