package com.bonait.bnframework.HBL.DataUtil;


import com.bonait.bnframework.HBL.Enum.DataFormat;

public class ByteLib {

    public static byte[] ToBytes(short value, DataFormat df) {
        byte[] b = new byte[2];
        b[0]=(byte)((value>>8)&0xff);
        b[1]=(byte)((value>>0)&0xff);
        return new ByteTransDataFormat().ByteTransDataFormat2(b,df,0);
    }

    public static byte[] ToBytes(short[] value,DataFormat df) {
        byte[] b = new byte[value.length*2];
        for (int i  = 0; i < value.length; i++)
        {
            b[i*2]=(byte)((value[i]>>8)&0xff);
            b[i*2+1]=(byte)((value[i]>>0)&0xff);
        }
        return new ByteTransDataFormat().ByteTransDataFormat2(b,df,0);
    }

    public static byte[] ToBytes(float value,DataFormat df) {
        int tempValue = Float.floatToRawIntBits(value);
        byte[] b = new byte[4];
        b[0]=(byte)((tempValue>>24)&0xff);
        b[1]=(byte)((tempValue>>16)&0xff);
        b[2]=(byte)((tempValue>>8)&0xff);
        b[3]=(byte)((tempValue>>0)&0xff);
        return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
    }

    public static byte[] ToBytes(float[] value,DataFormat df) {
        byte[] b = new byte[value.length*4];
        for (int i=0;i<value.length;i++)
        {
            int tempValue = Float.floatToRawIntBits(value[i]);
            b[i*4]=(byte)((tempValue>>24)&0xff);
            b[i*4+1]=(byte)((tempValue>>16)&0xff);
            b[i*4+2]=(byte)((tempValue>>8)&0xff);
            b[i*4+3]=(byte)((tempValue>>0)&0xff);
        }
        return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
    }

    public static byte[] ToBytes(int value,DataFormat df) {
        byte[] b = new byte[4];
        b[0]=(byte)((value>>24)&0xff);
        b[1]=(byte)((value>>16)&0xff);
        b[2]=(byte)((value>>8)&0xff);
        b[3]=(byte)((value>>0)&0xff);
        return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
    }

    public static byte[] ToBytes(int[] value,DataFormat df) {
        byte[] b = new byte[value.length*4];
        for (int i=0;i<value.length;i++)
        {
            b[i*4]=(byte)((value[i]>>24)&0xff);
            b[i*4+1]=(byte)((value[i]>>16)&0xff);
            b[i*4+2]=(byte)((value[i]>>8)&0xff);
            b[i*4+3]=(byte)((value[i]>>0)&0xff);
        }
        return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0);
    }

    public static boolean GetBit(byte value,int offset)
    {
        if (offset > 8 || offset < 1) return false;
        return (value & 1 << offset - 1) == 0 ? false : true;
    }

    public static byte SetBit(byte value,int offset, boolean val)
    {
        if (offset > 8 || offset < 1) return value;
        int ConvertValue = 1 << offset - 1;
        return (byte)(val ? value | ConvertValue : value & ~ConvertValue);
    }
}
