Showing posts with label Conversion. Show all posts
Showing posts with label Conversion. Show all posts

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.

How to Convert an InputStream into a Byte Array in Java?

Sometimes, one has an input stream and would like to retrieve the content in a byte array. Unfortunately, Java does not deliver a suitable method for this. Fortunately, the Apache Commons library provides a solution:
byte[] ba = { -1, 2, -3, 4, 0, 66 };
InputStream bais = new ByteArrayInputStream(ba);

byte[] retr = IOUtils.toByteArray(bais);

System.out.println("Expected  : " + Arrays.toString(ba));
System.out.println("Retrieved : " + Arrays.toString(retr));
The generated output is:
Expected  : -1 2 -3 4 0 66 
Retrieved : -1 2 -3 4 0 66
This code example is also available from Github, in the Java-Core-Examples directory.

More Java tips & tricks here.