package Tools;

/**
 * Tools for manipulating hexadecimal strings.
 */
public class Hex {
	static byte[] binaryToHexMap, hexToBinaryMap;
	static {
		binaryToHexMap = new byte[16];
		hexToBinaryMap = new byte[128];
		for (int i=0; i<10; i++) {
			binaryToHexMap[i] = (byte) (((byte) '0')+i);
			hexToBinaryMap[((byte) '0')+i] = (byte) i;
		}
		for (int i=0; i<6; i++) {
			binaryToHexMap[10+i] = (byte) (((byte) 'A')+i);
			hexToBinaryMap[((byte) 'A')+i] = (byte) (10+i);
		}
	}

	public static byte[] bytesToHex(byte[] binary) {
		byte[] outBuf = new byte[binary.length*2];
		int i,j;
		for (i=0,j=0; i<binary.length; i++, j+=2) {
			outBuf[j]	= binaryToHexMap[(binary[i] >> 4) & 0x0f];
			outBuf[j+1]	= binaryToHexMap[binary[i] & 0x0f];
		}
		return outBuf;
	}

	public static byte[] hexToBytes(byte[] hex) {
		if ((hex.length & 0x01) != 0) {
			throw new RuntimeException("odd-length hex string");
		}
		byte[] outBuf = new byte[hex.length/2];
		int i,j;
		for (i=0,j=0; i<hex.length; i+=2, j++) {
			outBuf[j] = (byte) ((hexToBinaryMap[hex[i]]<<4)
					| hexToBinaryMap[hex[i+1]]);
		}
		return outBuf;
	}
}
