package co.dc.aptiv.utils;

/**
 * @describe: 字符串与ASCII码互转
 * @author: liuxinglong
 * @version: 2018/4/18 23:17
 */
public class CharacterConversionUtil {
    /**
     * 字符串转ASCII
     *
     * @param str 字符串
     * @return int[] ascii码数据
     */
    public byte[] String2ASCII(String str) {
        char[] c = str.toCharArray();
        byte[] ascii = new byte[c.length];
        for (int i = 0; i < c.length; i++) {
            ascii[i] = (byte) c[i];
        }
        return ascii;
    }

    /**
     * ASCII转字符串
     *
     * @param ascii asscii码数组
     * @return String 字符串
     */
    public String ASCII2String(int[] ascii) {
        StringBuffer sb = new StringBuffer(ascii.length);
        for (int i = 0; i < ascii.length; i++) {
            sb.append((char) ascii[i]);
        }
        return sb.toString();
    }

    /**
     * 字符串转十六进制
     *
     * @param str
     * @return
     */
    public String String2HexString(String str) {
        byte[] ascii = String2ASCII(str);
        StringBuffer sb = new StringBuffer(ascii.length);
        for (int i = 0; i < ascii.length; i++) {
            //将十进制ascii码转换成十六进制ascii码
            sb.append(Integer.toHexString(ascii[i]));
            if (i != ascii.length - 1) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    /**
     * 十六进制转字符串
     *
     * @param str
     * @return
     */
    public String HexString2String(String str) {
        String[] strArray = str.split(" ");
        int[] ascii = new int[strArray.length - 3];
        int j = 0;
        for (int i = 0; i < strArray.length; i++) {
            //如果是开始、回车、换行则直接跳过
            boolean flag = "02".equals(strArray[i]) || "0D".equals(strArray[i]) || "0A".equals(strArray[i]);
            if (flag) {
                continue;
            }
            //将十六进制ascii码转换成十进制ascii码
            ascii[j] = Integer.parseInt(strArray[i], 16);
            j++;
        }
        return ASCII2String(ascii);
    }


    /**
     * 十六进制转字符串
     *
     * @param bytes
     * @return
     */
    public String HexString2String(byte[] bytes) {
        int[] ascii = new int[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            //将十六进制ascii码转换成十进制ascii码
            ascii[i] = bytes[i];
        }
        return ASCII2String(ascii);
    }

}
