package com.sunyard.chsm.sdf.util;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * @author liulu
 * @version V1.0
 * @since 2024/11/06
 */
public abstract class LangUtils {


    public static byte[] removeLastZero(byte[] bytes) {
        if (bytes == null) {
            return bytes;
        }
        int len = bytes.length;
        for (int i = len - 1; i >= 0; i--) {
            if (bytes[i] != 0) {
                return Arrays.copyOfRange(bytes, 0, i + 1);
            }
        }
        return bytes;
    }

    public static byte[] merge(byte[]... bytes) {
        int newLen = Arrays.stream(bytes).mapToInt(it -> it.length).sum();
        byte[] res = new byte[newLen];

        int mergedLen = 0;
        for (byte[] item : bytes) {
            System.arraycopy(item, 0, res, mergedLen, item.length);
            mergedLen += item.length;
        }
        return res;
    }

    public static byte[] toByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }

    public static byte[] toByteArray(long i) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.putLong(i);
        return buffer.array();
    }

    public static int toInt(byte[] bytes) {
        if (bytes == null || bytes.length != Integer.BYTES) {
            throw new IllegalArgumentException("转int需要4个字节");
        }
        int result = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (3 - i) * 8;
            result += (bytes[i] & 0xFF) << shift;
        }
        return result;
    }

    public static long toLong(byte[] bytes) {
        if (bytes == null || bytes.length != Long.BYTES) {
            throw new IllegalArgumentException("转long需要8个字节");
        }
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        return buffer.getLong();
    }
}
