Write a Java Program to Convert Byte Array to Hexadecimal

In Java, it is quite common to convert a byte array to its hexadecimal representation.

This can be useful when you need to transmit binary data over a text-based channel, such as a socket, or if you want to display binary data in a more human-readable format.

In this tutorial, we will discuss how to convert a byte array to its hexadecimal representation in Java.


Create a Byte Array

Before we can convert a byte array to its hexadecimal representation, we need to create a byte array.

Here’s an example of how to create a byte array in Java:

byte[] byteArray = { 0x0f, 0x1e, 0x2d, 0x3c };

This creates a byte array with four elements, each containing a hexadecimal value.

In this case, the first element is 0x0f, the second element is 0x1e, the third element is 0x2d, and the fourth element is 0x3c.

Convert the Byte Array to Hexadecimal

Once we have our byte array, we can convert it to its hexadecimal representation.

Here’s an example of how to do this in Java:

StringBuilder stringBuilder = new StringBuilder();
for (byte b : byteArray) {
    stringBuilder.append(String.format("%02X", b));
}
String hexString = stringBuilder.toString();

This code creates a StringBuilder object to hold the hexadecimal representation of the byte array.

It then iterates over each byte in the byte array, using the String.format() method to convert the byte to a two-digit hexadecimal string.

The two-digit format specifier, “%02X”, ensures that each hexadecimal string is padded with leading zeros if necessary.

Finally, the StringBuilder is converted to a String using the toString() method.

Display the Hexadecimal Representation

Now that we have the hexadecimal representation of the byte array, we can display it in the console or in a GUI window.

Here’s an example of how to display the hexadecimal representation in the console:

System.out.println(hexString);

This code simply prints the hexadecimal representation of the byte array to the console.


Conclusion

In this tutorial, we discussed how to convert a byte array to its hexadecimal representation in Java.

This can be useful in a variety of situations, such as when you need to transmit binary data over a text-based channel, or when you want to display binary data in a more human-readable format.

By following the steps outlined above, you can easily convert a byte array to its hexadecimal representation in Java.