To convert a byte array to a hexadecimal string and vice versa in Java, you can use the javax.xml.bind.DatatypeConverter
class. Here's how you can do it:
1. Convert Byte Array to Hexadecimal String:
java
import javax.xml.bind.DatatypeConverter;
public class ByteArrayToHexExample {
public static void main(String[] args) {
byte[] byteArray = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" in ASCII
String hexString = DatatypeConverter.printHexBinary(byteArray);
System.out.println("Hexadecimal String: " + hexString);
}
}
In this example, the DatatypeConverter.printHexBinary
method converts the byte array to a hexadecimal string representation.
2. Convert Hexadecimal String to Byte Array:
java
import javax.xml.bind.DatatypeConverter;
public class HexToByteArrayExample {
public static void main(String[] args) {
String hexString = "48656C6C6F"; // "Hello" in hexadecimal
byte[] byteArray = DatatypeConverter.parseHexBinary(hexString);
System.out.println("Byte Array: " + new String(byteArray));
}
}
In this example, the DatatypeConverter.parseHexBinary
method converts the hexadecimal string back to a byte array. We then create a new String
from the byte array to display the original text.
To use the DatatypeConverter
class, you don't need to add any external libraries, as it's part of the Java SE API. This approach is suitable for basic use cases. If you need more advanced or custom functionality, you might consider using external libraries or implementing the conversion yourself using bitwise operations.
Comments
Post a Comment