Hex { public static final String encode(int i) { char[] cbuf = new char[8]; int charPos = cbuf.length - 1; do { cbuf[charPos--] = DIGITS[i & 0xF]; i >>>= 4; cbuf[charPos--] = DIGITS[i & 0xF]; i >>>= 4; } while (i != 0); return new String(cbuf, charPos + 1, cbuf.length - charPos - 1); } private  Hex(); static final String encode(int i); static final String encode(final byte b); static final String encode(final byte[] b); static final byte[] decode(final String hex);  }
@Test public final void testEncode() { for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) { final String expected = String.format("%02X", Integer.valueOf(i & 0xFF)); final String actual = Hex.encode(new byte[] { (byte) i }); Assert.assertEquals(expected, actual); } }
@Test public final void testEncodeInt() { final Map<Integer, String> values = new HashMap<Integer, String>(); values.put(Integer.valueOf(0x00), "00"); values.put(Integer.valueOf(0xF), "0F"); values.put(Integer.valueOf(0xFF), "FF"); values.put(Integer.valueOf(-1), "FFFFFFFF"); for (Map.Entry<Integer, String> entry : values.entrySet()) { final String expected = entry.getValue(); final String actual = Hex.encode(entry.getKey().intValue()); Assert.assertEquals(expected, actual); } }