Tulips in snow

Java Byte Array as a Hex String – The Easy Way

There are lots of solutions for converting a Java byte array to a hexadecimal string.  Most work just fine, but recent versions of Java contain a utility class in the javax.xml.bind package to do this for you so you don’t have to write it yourself.  The utility class is DatatypeConverter, and the method is printHexBinary.  While apparently not as fast as some implementations,  DatatypeConverter.printHexBinary has two advantages:

  1. It’s build into the JRE – no coding required.
  2. Thus, less code in your project for you to test, maintain, checkout, etc.

Here’s how it works


import javax.xml.bind.DatatypeConverter;

....

 //print hex string version of HELLO WORLD
 byte[] helloBytes = "HELLO WORLD".getBytes();
 String helloHex = DatatypeConverter.printHexBinary(helloBytes);
 System.out.printf("Hello hex: 0x%s\n", helloHex);

 //convert hex-encoded string back to original string
 byte[] decodedHex = DatatypeConverter.parseHexBinary(helloHex);
 String decodedString = new String(decodedHex, "UTF-8");
 System.out.printf("Hello decoded : %s\n", decodedString);

And here’s the program output:

Hello hex: 0x48454C4C4F20574F524C44
Hello decoded : HELLO WORLD

2 thoughts on “Java Byte Array as a Hex String – The Easy Way

Leave a Reply

Your email address will not be published. Required fields are marked *