Java is a new language and the standard library is still filling in. One of the most common requests I see on the Java newsgroups and developer web pages is: how do you convert an integer to a hexadecimal string? The java.lang.Integer class does not have a toHexString method yet. People need this for all kinds of things, from displaying color values to debugging byte-level data.
Rather than making a whole package for something this simple, I just wrote a function that anyone can cut and paste into their program. Here it is:
public String toHex(int n)
{
String h = "" ;
int r=0;
int q=0;
int nn=n ;
do
{
r=nn % 16 ;
nn= nn / 16 ;
switch (r)
{
case 10: h = "A" + h; break ;
case 11: h = "B" + h; break ;
case 12: h = "C" + h; break ;
case 13: h = "D" + h; break ;
case 14: h = "E" + h; break ;
case 15: h = "F" + h; break ;
default: h = r + h; break ;
}
}
while (nn > 0) ;
return h ;
}
The logic is the standard division-remainder algorithm. You divide the number by 16 repeatedly. Each remainder gives you one hex digit, from least significant to most significant. The switch statement converts remainders 10 through 15 into the letters A through F. For remainders 0 through 9, the digit is the same in hex as in decimal, so the default case handles those.
The hex string is built by prepending each new digit, so the digits end up in the right order without needing to reverse the string at the end. Simple and correct.
To use it, just paste the method into your class and call toHex(255), which returns "FF". Or toHex(16) returns "10". It handles zero correctly and works for any non-negative int value.
I expect Sun will add a toHexString method to java.lang.Integer in a future release of the JDK. When they do, this function becomes obsolete, and that is fine. The whole point of contributing something like this is to fill a gap while the gap exists. Right now, people need it, so here it is.
Java is growing fast. There are things missing from the standard library that will get filled in over time. In the meantime, developers sharing small utility functions like this helps everyone move faster. You should not have to re-derive the hex conversion algorithm from scratch just because the standard library does not include it yet.
If you find this useful, go ahead and use it. No restrictions. Copy it, modify it, put it in your applet or application. That is what it is for.