package org.spbu.bdd.util;

public class ByteUtil {
	public static int byteToInt(byte b) {
		return b&0xFF;
	}
	
	//Direct
	public static int twoBytesToInt(byte hi, byte lo) {
		return (byteToInt(hi) << 8) + byteToInt(lo);
	}
	
	public static int halfByteToInt(byte b, boolean hi) {
		return (byteToInt(b) >> (hi ? 4 : 0)) & 0xF;  
	}
	
	public static int threeBytesAndHalfToInt(byte hi, byte m, byte lo, int rem) {
		return (byteToInt(hi) << 20) + (byteToInt(m) << 12) + (byteToInt(lo) << 4) + rem;
	}
	
	
	//Reverse
	public static void intToTwoBytes(int val, byte[] arr, int offset) {
		arr[offset] = (byte)((val >> 8) & 0xFF);
		arr[offset+1] = (byte) (val & 0xFF); 
	}
	
	public void intToHalfByte(int val, byte[] arr, int offset, boolean hi) {
		arr[offset] |= val << (hi ? 4 : 0); 
	}
	
	public static byte twoHalvesToByte(int hi, int lo) {
		return (byte)((hi << 4) | lo); 
	}
	
	public static int intToThreeBytesAndHalf(int val, byte[] arr, int offset) {
		arr[offset] = (byte)((val >> 20) & 0xFF);
		arr[offset+1] = (byte)((val >> 12) & 0xFF);
		arr[offset+2] = (byte)((val >> 4) & 0xFF);
		return val & 0xF;		
	}
	
	
	
	public static void main(String [] args) {
		byte b = (byte)254;
		System.out.println(b);
		System.out.println(halfByteToInt(b, true));
		System.out.println(halfByteToInt(b, false));
		
		b = (byte)65;
		System.out.println(halfByteToInt(b, true));
		System.out.println(halfByteToInt(b, false));
	}
}
