package com.changfa.utils;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName ByteUtil
 * @Description: TODO
 * @Author lingxin
 * @Date 2022/7/13
 **/
public class ByteUtil {

    /**
     * 合并多个byte数组
     *
     * @param values
     * @return
     */
    public static byte[] byteMergerAll(byte[]... values) {
        int length_byte = 0;
        for (int i = 0; i < values.length; i++) {
            length_byte += values[i].length;
        }
        byte[] all_byte = new byte[length_byte];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] b = values[i];
            System.arraycopy(b, 0, all_byte, countLength, b.length);
            countLength += b.length;
        }
        return all_byte;
    }

    /**
     * 格式化参数
     *
     * @param str
     * @param count
     * @return
     */
    public byte[] fillParam(String str, int count) throws UnsupportedEncodingException {
        if (str.getBytes("GBK").length >= count) {
            return str.getBytes("GBK");
        }
        byte[] data = str.getBytes("GBK");
        byte[] empty = new byte[count - data.length];
        for (int i = 0; i < empty.length; i++) {
            empty[i] = 32;
        }
        return byteMergerAll(empty, data);
    }

    /**
     * 截取数组
     *
     * @param original
     * @param begin
     * @param end
     * @return
     */
    public byte[] getByteByIndex(byte[] original, int begin, int end) {
        byte[] result = new byte[end - begin + 1];
        int j = 0;
        for (int i = begin; i <= end; i++) {
            result[j] = original[i];
            j++;
        }
        return result;
    }

}
