package fr.umlv.ir2.util;

/**
 * This utility class offers conversion static methods between primitive types 
 * and byte arrays for network transport.
 * @author duris
 */
public class Converter {

	public final static int LONG_SIZE = 8;

	/**
	 * Returns the long primitive value being represented by the argument byte 
	 * array in network order (big endian). The lowest index in the array 
	 * contains the most significant byte of the long value.
	 * @param array the byte array representing a long value in network order.
	 * @return the long value represented by the byte array.
	 * @throws IllegalArgumentException if the byte array size is incompatible 
	 * with the long representation. 
	 */
	public static long byteArrayToLong(byte[] array) throws IllegalArgumentException {
		if (array.length != LONG_SIZE)
			throw new IllegalArgumentException("Incompatible size of byte array for a long: " + array.length);
		long lu = 0;
		for(int b = 0; b<LONG_SIZE; b++) {
			lu = lu << 8;
			lu |= (array[b] & 0xFF);
		}
		return lu;
	}

	/**
	 * Assigns in the specified array the bytes of the specified long 
	 * primitive value in network order representation (big endian). 
	 * The most significant byte in the long value is stored at the lowest 
	 * index in the array.
	 * @param value the primitive long value.
	 * @param array the byte array representing a long value in network order.
	 * @throws IllegalArgumentException if the byte array size is incompatible with 
	 * the long representation. 
	 */
	public static void longToByteArray(long value, byte[] array) {
		if (array.length != LONG_SIZE)
			throw new IllegalArgumentException("Incompatible size of byte array for a long: " + array.length);
		for(int b = LONG_SIZE-1; b>=0; b--) {
			array[b] = (byte) (value & 0xFF);
			value = value >> 8;
		}
	}
}
