Converting A String To Hexadecimal In Java
To convert a string to a hexadecimal string in Java, you can use the encodeHexString method of the org.apache.commons.codec.binary.Hex class.
To convert a string to a hexadecimal string in Java, you can use the encodeHexString method of the org.apache.commons.codec.binary.Hex class. This requires the Apache Commons Codec library (commons-codec). Here is an example:
import org.apache.commons.codec.binary.Hex;
import java.nio.charset.StandardCharsets;
String input = "Hello World";
String hexString = Hex.encodeHexString(input.getBytes(StandardCharsets.UTF_8));
System.out.println(hexString); // prints "48656c6c6f20576f726c64"Alternatively, you can use a loop to manually convert the string to a hexadecimal string:
String input = "Hello World";
StringBuilder hexString = new StringBuilder();
for (char c : input.toCharArray()) {
hexString.append(Integer.toHexString((int) c));
}
System.out.println(hexString.toString()); // prints "48656c6c6f20576f726c64" (Note: output varies by character encoding; drops leading zeros for values < 0x10)You can also use the String.format method to ensure consistent two-digit padding:
String input = "Hello World";
StringBuilder hexString = new StringBuilder();
for (char c : input.toCharArray()) {
hexString.append(String.format("%02x", (int) c));
}
System.out.println(hexString.toString()); // prints "48656c6c6f20576f726c64"For Java 19+, consider using the built-in java.util.HexFormat to avoid external dependencies.