Friday 10 August 2012

How to Convert a Byte Array Into an Hexadecimal String?

Trying to convert a byte array into an hexadecimal and back to the same byte array manually, can be tricky. The Hex class of the Apache Commons library offers a solution:
byte[] ba = { 4, 55, -27, 99, 42, 0, -1 };

String toHex = Hex.encodeHexString(ba);
byte[] retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));

ba = new byte[0];
toHex = Hex.encodeHexString(ba);
retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));
The generated output is:
Hexadecimal : 0437e5632a00ff
Expected    : [4, 55, -27, 99, 42, 0, -1]
Retrieved   : [4, 55, -27, 99, 42, 0, -1]

Hexadecimal :
Expected    : []
Retrieved   : []
More Java tips & tricks here.

No comments:

Post a Comment