Show a number in hex form
Submitted by jhallida on Sat, 05/08/2010 - 22:14
In Java, the 'toHexString' method will convert a number into a string that represents that number in hex form. However, this string is not usually formatted in the way that most people would expect - it does not begin with '0x' and does not contain leading zeros. Here is a function that does just that.
This method works with a long, but a similar method could be created for other data types such as ints.
/**
* Convert a long into a hex string.
*
* @param decimal the long
* @return the formatted hex string
*/
public static String convertToHex(long decimal) {
String x = Long.toHexString(decimal);
if (x.length() <= 2) {
while (x.length() < 2) {
x = "0" + x;
}
} else if (x.length() <= 4) {
while (x.length() < 4) {
x = "0" + x;
}
} else if (x.length() <= 6) {
while (x.length() < 6) {
x = "0" + x;
}
} else {
while (x.length() < 8) {
x = "0" + x;
}
}
x = "0x" + x;
return x;
}
