How to convert a bytearray to a hex string and back
byte array -> Hex
(originaly found this on
http://rgagnon.com/javadetails/java-0596.html and want to preserve this for my work):
public class HexUtil
{
private static final byte[] hexalphabet = "0123456789ABCDEF".getBytes();
public static String toHex( byte [] raw )
{
if ( raw == null )
return null; StringBuilder hex = new StringBuilder( 2 * raw.length );
for ( byte b : raw )
hex.append(hexalphabet[(b & 0xF0) >> 4])
.append(hexalphabet[(b & 0x0F)]); return hex.toString();
}
}
Hex-String -> byte array
public static byte[] fromHex(String s)
{
byte[] b = new byte[s.length() / 2];
for (int i = 0, j=0; i < b.length; i++, j=i*2)
b[i] = (byte) Integer.parseInt(s.substring(j, j + 2), 16);
return b;
}