Java: convert a byte array to a hex string?

Java: convert a byte array to a hex string?

You can convert a byte array to a hexadecimal string in Java by iterating through the byte array and converting each byte to its hexadecimal representation. Here's a sample code snippet to achieve this:

public class ByteArrayToHexString { public static void main(String[] args) { byte[] byteArray = { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64 }; // Convert the byte array to a hexadecimal string String hexString = bytesToHex(byteArray); // Print the hexadecimal string System.out.println(hexString); } public static String bytesToHex(byte[] bytes) { StringBuilder hexStringBuilder = new StringBuilder(2 * bytes.length); for (byte b : bytes) { // Convert each byte to a two-character hexadecimal representation hexStringBuilder.append(String.format("%02x", b)); } return hexStringBuilder.toString(); } } 

In this example:

  1. We have a byte array byteArray containing some byte values.
  2. We define a bytesToHex method that takes a byte array as input and converts it to a hexadecimal string.
  3. Inside the bytesToHex method, we iterate through each byte in the input array and use String.format("%02x", b) to convert it to a two-character hexadecimal representation and append it to a StringBuilder.
  4. Finally, we return the resulting hexadecimal string.

When you run the code, it will convert the byteArray to a hexadecimal string and print it:

48656C6C6F20576F726C64 

This is the hexadecimal representation of the bytes in the byteArray. You can replace byteArray with your own byte array if needed.


More Tags

client-certificates twitter-bootstrap android-appbarlayout java-threads cornerradius ksh kubernetes-cronjob rgba pagination npm-start

More Java Questions

More Chemistry Calculators

More Trees & Forestry Calculators

More Fitness-Health Calculators

More Bio laboratory Calculators