package org.tio.sitexxx.service.service.pay.utils;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-11-26 11:40
 *    desc   : 十六进制转换
 * </pre>
 */
public class HexStringByte {
    /**
     * java字节码转字符串
     * @param bts
     * @return
     */

    public static String byteToHex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    /**
     * hex2byte.
     *
     * @param hexStr hexStr
     * @return byte[]
     */
    public static byte[] hex2byte(String hexStr) {
        byte[] bts = new byte[hexStr.length() / 2];
        for (int i = 0, j = 0; j < bts.length; j++) {
            bts[j] = (byte) Integer.parseInt(hexStr.substring(i, i + 2), 16);
            i += 2;
        }
        return bts;
    }

    /**
     * 字符串转java字节码
     * @param b
     * @return
     */
    public static byte[] hexToByte(byte[] b) {
        if ((b.length % 2) != 0) {
            throw new IllegalArgumentException("长度不是偶数");
        }
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个进制字节
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        b = null;
        return b2;
    }
}
