package com.xxxxtech.srac.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * FileName：StringUtils <br>
 * CreateTime： 2019-08-14 18:02 <br>
 * Description：<br>
 * 字符串处理工具
 *
 * @author Dawson <br>
 * @version v0.1  <br>
 * @since JDK 1.8
 */
public class StringUtils {

    /**
     * 16进制的字符串转换成字节数组
     *
     * @param hexString
     * @return 字节数组
     */
    public static byte[] hexStrToBinaryStr(String hexString) {
        //去除空格
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;
        //两位为一个字符
        byte[] bytes = new byte[len / 2];

        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }

        return bytes;
    }


    /**
     * 普通的字符串转换成字节数组
     *
     * @param hexString
     * @return 转换后的字节数组
     **/
    public static byte[] toByteArray(String hexString) {
        if (hexString.isEmpty()) {
            throw new IllegalArgumentException("this hexString must not be empty");
        }

        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }


    /**
     * 16进制字节流转换成字符串
     *
     * @param
     * @return String
     * @throws IOException
     */
    public static String bytesToHex(InputStream msg) throws IOException {
        System.out.println("-----》》解析流："+msg);
        int a;
        byte[] bytes = new byte[1024];
        try {
            a = msg.read(bytes);
        } catch (Exception e) {
            return "0";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < a; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
