package com.inspect.base.core.utils;

import java.nio.charset.Charset;

public class ByteUtil {
    public static byte[] getBytes(short data) {
        byte[] bytes = new byte[]{(byte) (data & 255), (byte) ((data & '\uff00') >> 8)};
        return bytes;
    }

    public static byte[] getBytes(char data) {
        byte[] bytes = new byte[]{(byte) data, (byte) (data >> 8)};
        return bytes;
    }

    public static byte[] getBytes(int data) {
        byte[] bytes = new byte[]{(byte) (data & 255), (byte) ((data & '\uff00') >> 8), (byte) ((data & 16711680) >> 16), (byte) ((data & -16777216) >> 24)};
        return bytes;
    }

    public static byte[] getBytes(long data) {
        byte[] bytes = new byte[]{(byte) ((int) (data & 255L)), (byte) ((int) (data >> 8 & 255L)), (byte) ((int) (data >> 16 & 255L)), (byte) ((int) (data >> 24 & 255L)), (byte) ((int) (data >> 32 & 255L)), (byte) ((int) (data >> 40 & 255L)), (byte) ((int) (data >> 48 & 255L)), (byte) ((int) (data >> 56 & 255L))};
        return bytes;
    }

    public static byte[] getBytes(float data) {
        int intBits = Float.floatToIntBits(data);
        return getBytes(intBits);
    }

    public static byte[] getBytes(double data) {
        long intBits = Double.doubleToLongBits(data);
        return getBytes(intBits);
    }

    public static byte[] getBytes(String data, String charsetName) {
        Charset charset = Charset.forName(charsetName);
        return data.getBytes(charset);
    }

    public static byte[] getBytes(String data) {
        return getBytes(data, "GBK");
    }

    public static short getShort(byte[] bytes) {
        return (short) (255 & bytes[0] | '\uff00' & bytes[1] << 8);
    }

    public static char getChar(byte[] bytes) {
        return (char) (255 & bytes[0] | '\uff00' & bytes[1] << 8);
    }

    public static int getInt(byte[] bytes) {
        return 255 & bytes[0] | '\uff00' & bytes[1] << 8 | 16711680 & bytes[2] << 16 | -16777216 & bytes[3] << 24;
    }

    public static long getLong(byte[] bytes) {
        return 255L & (long) bytes[0] | 65280L & (long) bytes[1] << 8 | 16711680L & (long) bytes[2] << 16 | 4278190080L & (long) bytes[3] << 24 | 1095216660480L & (long) bytes[4] << 32 | 280375465082880L & (long) bytes[5] << 40 | 71776119061217280L & (long) bytes[6] << 48 | -72057594037927936L & (long) bytes[7] << 56;
    }

    public static float getFloat(byte[] bytes) {
        return Float.intBitsToFloat(getInt(bytes));
    }

    public static double getDouble(byte[] bytes) {
        long l = getLong(bytes);
        System.out.println(l);
        return Double.longBitsToDouble(l);
    }

    public static String getString(byte[] bytes, String charsetName) {
        return new String(bytes, Charset.forName(charsetName));
    }

    public static String getString(byte[] bytes) {
        return getString(bytes, "GBK");
    }
}
