How can you convert a byte array to a hexadecimal string and vice versa?

 

You can convert a byte array to a hexadecimal string and vice versa in Java using the Hex class from the org.apache.commons.codec.binary package, which is part of the Apache Commons Codec library. Here's how you can do it:

1. Convert Byte Array to Hexadecimal String:

java
import org.apache.commons.codec.binary.Hex; public class ByteArrayToHexExample { public static void main(String[] args) { byte[] byteArray = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" in ASCII String hexString = Hex.encodeHexString(byteArray); System.out.println("Hexadecimal String: " + hexString); } }

In this example, the Hex.encodeHexString method converts the byte array to a hexadecimal string representation.

2. Convert Hexadecimal String to Byte Array:

java
import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; public class HexToByteArrayExample { public static void main(String[] args) { String hexString = "48656C6C6F"; // "Hello" in hexadecimal try { byte[] byteArray = Hex.decodeHex(hexString); System.out.println("Byte Array: " + byteArrayToString(byteArray)); } catch (DecoderException e) { System.err.println("Invalid hexadecimal string"); } } public static String byteArrayToString(byte[] byteArray) { StringBuilder sb = new StringBuilder(); for (byte b : byteArray) { sb.append((char) b); } return sb.toString(); } }

In this example, the Hex.decodeHex method converts the hexadecimal string back to a byte array. We also define the byteArrayToString method to convert the byte array to a readable string.

To use the Apache Commons Codec library, you need to add it to your project's dependencies. If you're using a build tool like Maven or Gradle, you can include the library as a dependency in your project's configuration file.

Please note that while the example above uses the Apache Commons Codec library, you can also achieve similar functionality using built-in Java classes like ByteBuffer and String. However, using a library like Apache Commons Codec can simplify the process and handle edge cases more gracefully.

Comments