- Java Program to Convert Byte Array to Hexadecimal
- Example 1: Convert Byte Array to Hex value
- Example 2: Convert Byte Array to Hex value using byte operations
- How to Convert and Print Byte array to Hex String in Java? Example
- The issue with Printing Byte arrays as String
- Benefits of Printing Byte array as Hex String in Java
- 2 ways to Convert Byte Array to Hex String in Java
- Printing byte as hex java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Class HexFormat
Java Program to Convert Byte Array to Hexadecimal
To understand this example, you should have the knowledge of the following Java programming topics:
Example 1: Convert Byte Array to Hex value
public class ByteHex < public static void main(String[] args) < byte[] bytes = ; for (byte b : bytes) < String st = String.format("%02X", b); System.out.print(st); >> >
In the above program, we have a byte array named bytes . To convert byte array to a hex value, we loop through each byte in the array and use String ‘s format() .
We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .
This is a relatively slower process for large byte array conversion. We can dramatically increase the speed of execution using byte operations shown below.
Example 2: Convert Byte Array to Hex value using byte operations
public class ByteHex < private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) < char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) < int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; > return new String(hexChars); > public static void main(String[] args) < byte[] bytes = ; String s = bytesToHex(bytes); System.out.println(s); > >
The output of the program is the same as Example 1.
How to Convert and Print Byte array to Hex String in Java? Example
We often need to convert byte arrays to Hex String in Java, In order to print byte array contents in a readable format. Since many cryptographic algorithms e.g. MD5 return the hash value as a byte array, In order to see and compare that byte array, you need to convert the byte array to Hex String. As we have seen, while generating MD5 checksum of File, there are multiple ways to convert byte array to Hexadecimal String in Java. You can either write your own method, or you can use an open-source library e.g. Apache commons-codec to create Hex String from a byte array in Java. Commons codec provides a utility class Hex , which contains an encodeHexString() method to create Hex String from a byte array.
It’s one of the best options to genera te Hex String if you a re already using this library to generate MD5 hash values. In this Java tutorial, we will see what is the issue with printing byte array as normal String, and 2 examples to convert a byte array into Hexadecimal String in Java.
The issue with Printing Byte arrays as String
Some of you might be wondering, why can’t we u se String constructor wh ich accepts byte array e.g. new String(byte[]) . Well, the real issue with printing byte array is non-printable ASCII characters. Your MD5 checksum or any byte array may contain some non-printable characters, which means you can not compare two-byte arrays by looking at their String representation.
By the way, this is not a problem if yo u are encoding String in base64, a s they only use printable ASCII characters. In our code example of printing byte array as normal String, you can see different strings, generated from different byte arrays, looks the same.
Since 0, 5 and 6 represent non-printable characters ASCII characters NUL , ENQ and ACK , they are showing here a s white space he re. This issue can be resolved if we convert byte array to Hexadecimal String, and then print or display it.
Benefits of Printing Byte array as Hex String in Java
There are a couple of benefits of printing byte array as Hex String in Java. In fact, displaying byte array as Hex String is normal practice, especially when you want to see and compare MD5 hash or digest value, generated by the cryptographic algorithm.
1) It’s easy to display contents of byte array in a standard way, as byte array may contain non-printable characters.
2 ways to Convert Byte Array to Hex String in Java
As I said, there are multiple ways to generate hexadecimal String from byte array in Java e.g. including symbol array, and usi ng the String format method. In this Ja va program, we will see two examples to convert byte array to Hexadecimal String.
In the first example, we have used core Java, and in the second example, we have used Apache commons-codec library. It provides a utility class org.apache.commons.codec.binary.Hex , which can convert byte array to Hex String in Just one line.
I am big fan of using open source libraries, especially fo r production usage. By the way, we will also look issue with printing byte array as normal String, which may help you to understand need of converting byte array to Hex String before printing them.
import java.util.logging.Logger; import org.apache.commons.codec.binary.Hex; /** * Java program to convert Byte array to Hex String in Java. * This Java example uses core Java and Apache commons code to * generate Hexadecimal String from byte array in Java. * * @author Javin Paul */ public class ByteArrayToHexString < private static final Logger logger = Logger.getLogger(StringReplace.class.getName()); public static void main(String args[]) < //byte array with non printable characters byte[] bytes = new byte[]'a', 'b', 0, 5, 'c','d'>; byte[] nonprintable = new byte[]'a', 'b', 0, 6, 'c','d'>; //You can not print byte array as String because they may contain non printable //characters e.g. 0 is NUL, 5 is ENQ and 6 is ACK in ASCII format String value = new String(bytes); System.out.println(value); String str = new String(nonprintable); System.out.println(str); //Converting byte array to Hex String in Java for printing System.out.println("Byte array to Hex String in Java : " + bytesToHexString(bytes)); //Apache commons codec to convert byte array to Hex String in Java String hex = Hex.encodeHexString(bytes); System.out.println("Byte array to Hexadecimal String using Apache commons: " + hex); > public static String bytesToHexString(byte[] bytes)< StringBuilder sb = new StringBuilder(); for(byte b : bytes)< sb.append(String.format("%02x", b&0xff)); > return sb.toString(); > > Output: ab cd ab cd Byte array to Hex String in Java : 616200056364 Byte array to Hexadecimal String using Apache commons: 616200056364
As I explained in the section issue with printing byte arrays, character after «ab» is not white space, it’s a NUL ASCII character, but showing as white space here. Try running this Java program on your machine, and copying the first line of output, you can only copy the first two characters.
That’s all on How to convert byte array to Hex String in Java. As I said, the byte array may contain some non-printable characters, which may produce a misleading value while printing them as normal String. It’s always best to display the contents of the byte array as a hex string in Java.
Printing byte as hex java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Class HexFormat
HexFormat converts between bytes and chars and hex-encoded strings which may include additional formatting markup such as prefixes, suffixes, and delimiters.
There are two factories of HexFormat with preset parameters of() and ofDelimiter(delimiter) . For other parameter combinations the withXXX methods return copies of HexFormat modified withPrefix(String) , withSuffix(String) , withDelimiter(String) or choice of withUpperCase() or withLowerCase() parameters.
For primitive to hexadecimal string conversions the toHexDigits methods include toHexDigits(byte) , toHexDigits(int) , and toHexDigits(long) , etc. The default is to use lowercase characters «0-9″,»a-f» . For conversions producing uppercase hexadecimal the characters are «0-9″,»A-F» . Only the HexFormat.isUpperCase() parameter is considered; the delimiter, prefix and suffix are not used.
For hexadecimal string to primitive conversions the fromHexDigits methods include fromHexDigits(string) , fromHexDigitsToLong(string) , and fromHexDigit(int) converts a single character or codepoint. For conversions from hexadecimal characters the digits and uppercase and lowercase characters in «0-9», «a-f», and «A-F» are converted to corresponding values 0-15 . The delimiter, prefix, suffix, and uppercase parameters are not used.
For byte array to formatted hexadecimal string conversions the formatHex methods include formatHex(byte[]) and formatHex(Appendable, byte[]) . The formatted output is a string or is appended to an Appendable such as StringBuilder or PrintStream . Each byte value is formatted as the prefix, two hexadecimal characters from the uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last. For conversions producing uppercase hexadecimal strings use withUpperCase() .
For formatted hexadecimal string to byte array conversions the parseHex methods include parseHex(CharSequence) and parseHex(char[], offset, length) . Each byte value is parsed from the prefix, two case insensitive hexadecimal characters, and the suffix. A delimiter follows each formatted value, except the last.
API Note: For example, an individual byte is converted to a string of hexadecimal digits using toHexDigits(int) and converted from a string to a primitive value using fromHexDigits(string) .
HexFormat hex = HexFormat.of(); byte b = 127; String byteStr = hex.toHexDigits(b); byte byteVal = (byte)hex.fromHexDigits(byteStr); assert(byteStr.equals("7f")); assert(b == byteVal); // The hexadecimal digits are: "7f"
For a comma ( «, » ) separated format with a prefix ( «#» ) using lowercase hex digits the HexFormat is:
HexFormat commaFormat = HexFormat.ofDelimiter(", ").withPrefix("#"); byte[] bytes = ; String str = commaFormat.formatHex(bytes); byte[] parsed = commaFormat.parseHex(str); assert(Arrays.equals(bytes, parsed)); // The formatted string is: "#00, #01, #02, #03, #7c, #7d, #7e, #7f"
For a fingerprint of byte values that uses the delimiter colon ( «:» ) and uppercase characters the HexFormat is:
HexFormat formatFingerprint = HexFormat.ofDelimiter(":").withUpperCase(); byte[] bytes = ; String str = formatFingerprint.formatHex(bytes); byte[] parsed = formatFingerprint.parseHex(str); assert(Arrays.equals(bytes, parsed)); // The formatted string is: "00:01:02:03:7C:7D:7E:7F"
This is a value-based class; use of identity-sensitive operations (including reference equality ( == ), identity hash code, or synchronization) on instances of HexFormat may have unpredictable results and should be avoided. The equals method should be used for comparisons.
This class is immutable and thread-safe.
Unless otherwise noted, passing a null argument to any method will cause a NullPointerException to be thrown.