
package com.ebts.common.utils.md5;

import com.google.common.primitives.Bytes;

import java.util.LinkedList;

/**
 * Byte工具
 *
 * @author yinzhennan
 * @version V1.0
 * @since 2020-08-27 09:28
 */
public class BytesUtils {

    public static final int FF = 0xFF;

    public static byte[] long2bytes(long v) {
        byte[] ret = new byte[]{0, 0, 0, 0, 0, 0, 0, 0};
        long2bytes(v, ret);
        return ret;
    }

    public static byte[] trim(byte[] bytes) {
        LinkedList<Byte> linkedList = new LinkedList<>(Bytes.asList(bytes));
        while(linkedList.getFirst() == 0){
            linkedList.remove(0);
        }
        return Bytes.toArray(linkedList);
    }

    public static long bytes2Long(byte[] input){
        final int size = input.length;
        if(size > 8){
            throw new IllegalArgumentException("输入参数最多8位");
        }
        int unsigned = input[0] & FF;
        long value = 0;
        value = value | unsigned;
        // 循环读取每个字节通过移位运算完成long的8个字节拼装
        for(int  i=1;i< size;++i){
            unsigned = input[i] & FF;
            value = value << 8 | unsigned;
        }
        return value;
    }

    private static void long2bytes(long v, byte[] b) {
        long2bytes(v, b, 0);
    }

    private static void long2bytes(long v, byte[] b, int off) {
        b[off + 7] = (byte)((int)v);
        b[off + 6] = (byte)((int)(v >>> 8));
        b[off + 5] = (byte)((int)(v >>> 16));
        b[off + 4] = (byte)((int)(v >>> 24));
        b[off + 3] = (byte)((int)(v >>> 32));
        b[off + 2] = (byte)((int)(v >>> 40));
        b[off + 1] = (byte)((int)(v >>> 48));
        b[off + 0] = (byte)((int)(v >>> 56));
    }
}
