Monday, October 9, 2006

Printing the Hex equivalent of a unicode character (Java)

/*
* Converts the byte to hex
*/

public String byteToHex(byte b) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' };
char[] array = { hexDigits[(b >> 4) & 0x0f], hexDigits[b & 0x0f] };
return new String(array);
}
/*
* Returns the hex equivalent of a character
*/

public String charToHex(char c) {
//get the hex of a higher byte
byte hi = (byte) (c >>> 8);
//get the hex equivalent of lower byte
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}