package com.sheep.jiuyan.samllsheep.utils;

/**
 * Created by kemllor on 2018/1/22.
 */

public class HexUtils {
    private static final String HEX_STR_POOL = "0123456789ABCDEF";
    private static StringBuffer buf = new StringBuffer();

    public static byte[] hexStr2Bytes(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() / 2];

            for (int i = 0; i < hexStr.length() / 2; ++i) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte) (high * 16 + low);
            }

            return result;
        }
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString != null && !hexString.equals("")) {
            hexString = hexString.toUpperCase();
            int length = hexString.length() / 2;
            char[] hexChars = hexString.toCharArray();
            byte[] d = new byte[length];

            for (int i = 0; i < length; ++i) {
                int pos = i * 2;
                byte h = charToByte(hexChars[pos]);
                byte l = charToByte(hexChars[pos + 1]);
                d[i] = (byte) (h << 4 | l);
            }

            return d;
        } else {
            return null;
        }
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String bytes2HexStr(byte[] datas) {
        if (datas != null && datas.length != 0) {
            buf.setLength(0);

            for (int i = 0; i < datas.length; ++i) {
                if ((datas[i] & 255) < 16) {
                    buf.append("0");
                }

                buf.append(Long.toHexString((long) (datas[i] & 255)));
            }

            return buf.toString();
        } else {
            return null;
        }
    }

    public static String byte2HexStr(byte data) {
        buf.setLength(0);
        buf.append("0x");
        if ((data & 255) < 16) {
            buf.append("0");
        }

        buf.append(Long.toHexString((long) (data & 255)));
        return buf.toString();
    }

    private HexUtils() {
    }
}
