package com.bonait.bnframework.HBL.DataUtil;




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

import java.nio.ByteBuffer;

public class IntLib {
    public static int ToInt(byte[] bytes, DataFormat df) {
        byte[] res=  new ByteTransDataFormat().ByteTransDataFormat4(bytes,df,0);
        return ByteBuffer.wrap(res).getInt();
    }

    public static int ToInt(short[] shorts, DataFormat df) {
        if (shorts.length<2) return 0;
        byte[] bytes= ByteLib.ToBytes(shorts,df);
        if (bytes.length!=4) return 0;
        return ByteBuffer.wrap(bytes).getInt();
    }

    public static int[] ToInts(byte[] bytes, DataFormat df) {
        byte[] tempBytes=new byte[bytes.length];
        if (bytes.length%4!=0)
        {
            int offset=4-bytes.length%4;
            tempBytes=new byte[bytes.length+offset];
        }
        for (int i=0;i<bytes.length;i++){tempBytes[i]=bytes[i];}
        int[] result = new int[tempBytes.length/4];
        for (int i=0; i<result.length; i++){
            byte[] res=  new ByteTransDataFormat().ByteTransDataFormat4(tempBytes,df,i*4);
            result[i]=ByteBuffer.wrap(res).getInt();
        }
        return result;
    }

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

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