/**
 * This class offers several base manipulation services (hexadecimal, binary, 2^n).
 * <BR>You can read the source of this class <A HREF="./Utils.java.html"> here</A>.
 */
public abstract class Utils {

	/**
	 * Returns 2^n, with n between 0 and 16.
	 */
	public static int Puiss2(int n) {
		return Puiss2[n];
	}

	/**
	 * Computes a String that represents num in binary format.
	 * @param num Number to convert.
	 * @param nbits Number of bits to output.
	 * @param sep Number of bits of each group separated by a space.
	 * @return A String made of nbits of num in binary format in groups of sep bits.
	 */
	public static String bin(int num, int nbits, int sep) {
		String ret = "";
		int i;

		for(i = 0 ; i < nbits ; i++) {
			if(((i % sep) == 0) && (i != 0))
				ret = " " + ret;
			if((num & Puiss2[i]) == 0)
				ret = "0" + ret;
			else
				ret = "1" + ret;
		}

		return ret;
	}

	/**
	 * Computes a String that represents num in hexadecimal format.
	 * @param num Number to convert.
	 * @param ndigits Number of digits to output.
	 * @param sep Number of digits of each group separated by a space.
	 * @return A String made of ndigits of num in hexadecimal format in groups of sep digits.
	 */
	public static String hex(int num, int ndigits, int sep) {
		String ret = "";
		int i;
		String HexDigits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

		for(i = 0 ; i < ndigits ; i ++) {
			if(((i % sep) == 0) && (i != 0))
				ret = " " + ret;
			ret = HexDigits[num & 0xF] + ret;
			num >>= 4;
		}

		return ret;
	}

	/**
	 * Computes the int value of the hexadecimal number represented by s.
	 * @param s An hexadecimal number only made of hexadecimal digits ; the conversion stops when an illagal character is encountered.
	 * @return The int value of the hexadecimal number represented by s.
	 */
	public static int hex2num(String s) {
		int i, ret = 0;
		char c;

		s = s.toUpperCase();
		for(i = 0 ; i < s.length() ; i++) {
			c = s.charAt(i);
			if((c >= '0') && (c <= '9'))
				c -= '0';
			else if((c >= 'A') && (c <= 'F')) {
				c = (char)(c - 'A' + 10);
			}
			else
				return ret;

			ret = (ret * 16) + (int)c;
		}

		return ret;
	}

// Private variables
	protected static final int Puiss2[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536};
}