To get a hexadecimal string representation of a byte array, you can use String.format()with %X the format specifier :
public static String asHex(byte buf[])
{
StringBuffer strbuf = new StringBuffer(buf.length * 2);
for (byte b : buf)
strbuf.append(String.format("%02X", b));
return strbuf.toString();
}
The following method gives the inverse operation, returning a representation of the byte array of the hexadecimal string. It uses Byte.parseByte()some bit offset to get two characters in one byte:
public static byte[] asBytes(String str)
{
if ((str.length() % 2) == 1) str = "0" + str;
byte[] buf = new byte[str.length() / 2];
int i = 0;
for (char c : str.toCharArray())
{
byte b = Byte.parseByte(String.valueOf(c), 16);
buf[i/2] |= (b << (((i % 2) == 0) ? 4 : 0));
i++;
}
return buf;
}
source
share