ByteUtil.java 1.67 KB
Newer Older
凌鑫's avatar
凌鑫 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
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;
    }

}