Showing posts with label String. Show all posts
Showing posts with label String. 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 Encode and Decode Data to Base64 in Java?

In order to encode a string (or a byte array) into Base64, and then decode it into its original state, one can use the following piece of code:
String s = "String to encode/decode in Base64 with DataTypeConverter";

String coded = DatatypeConverter.printBase64Binary(s.getBytes());
byte[] retr = DatatypeConverter.parseBase64Binary(coded);

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
System.out.println();
The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHdpdGggRGF0YVR5cGVDb252ZXJ0ZXI=
Expected  : String to encode/decode in Base64 with DataTypeConverter
Retrieved : String to encode/decode in Base64 with DataTypeConverter

For input/output streams, one can use the following:
String s = "String to encode/decode in Base64 using streams";

ByteArrayOutputStream collect = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(collect);

b64os.write(s.getBytes());
b64os.close();

byte[] ba = collect.toByteArray();
String coded = new String(ba);

InputStream is = new ByteArrayInputStream(ba);
Base64InputStream b64is = new Base64InputStream(is);

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

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
The above uses an external library to convert the InputStream into a byte array. The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHVzaW5nIHN0cmVhbXM=
Expected  : String to encode/decode in Base64 using streams
Retrieved : String to encode/decode in Base64 using streams
The code examples are available from Github, in the Java-Core-Examples directory.

More Java tips & tricks here.