Integer to two digits hex in Java

String.format("%02X", value);

If you use X instead of x as suggested by aristar, then you don't need to use .toUpperCase().


Integer.toHexString(42);

Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)

Note that this may give you more than 2 digits, however! (An Integer is 4 bytes, so you could potentially get back 8 characters.)

Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):

Integer.toHexString(0x100 | 42).substring(1)

Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java.


String.format("%02X", (0xFF & value));    

Use Integer.toHexString(). Dont forget to pad with a leading zero if you only end up with one digit. If your integer is greater than 255 you'll get more than 2 digits.

StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
    sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();