Here are a few Java examples of converting between String or ASCII to and from Hexadecimal.
- Apache Commons Codec – Hex
- Integer
- Bitwise
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
1. Apache Commons Codec
Both Hex.encodeHex and Hex.decodeHex can convert String to Hex and vice versa.
pom.xml
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
HexUtils.java
package com.favtuts.converter;
import java.nio.charset.StandardCharsets;
import org.apache.commons.codec.binary.Hex;
public class HexUtils {
public static String convertStringToHex(String str) {
// display in uppercase
//char[] chars = Hex.encodeHex(str.getBytes(StandardCharsets.UTF_8), false);
// display in lowercase, default
char[] chars = Hex.encodeHex(str.getBytes(StandardCharsets.UTF_8));
return String.valueOf(chars);
}
public static String convertHexToString(String hex) {
String result = "";
try {
byte[] bytes = Hex.decodeHex(hex);
result = new String(bytes, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid Hex format!");
}
return result;
}
public static void main(String[] args) {
String input = "a";
System.out.println("input : " + input);
String hex = convertStringToHex(input);
System.out.println("hex : " + hex);
String result = convertHexToString(hex);
System.out.println("result : " + result);
}
}
Output
input : a
hex : 61
result : a
2. Integer
This example is easy to understand, use JDK Integer APIs like Integer.toHexString and Integer.parseInt(hex, 16) to convert the String to Hex and vice versa.
The idea is convert String <==> Decimal <==> Hex, for example char a, decimal is 97, hex is 61.
HexUtils2.java
package com.favtuts.converter;
public class HexUtils2 {
// Char -> Decimal -> Hex
public static String convertStringToHex(String str) {
StringBuilder hex = new StringBuilder();
// loop chars one by one
for (char temp : str.toCharArray()) {
// convert char to int, for char 'a' decimal 97
int decimal = (int) temp;
// convert int to hex, for decimal 97 hex 61
hex.append(Integer.toHexString(decimal));
}
return hex.toString();
}
// Hex -> Decimal -> Char
public static String convertHexToString(String hex) {
StringBuilder result = new StringBuilder();
// split into two chars per loop, hex, 0A, 0B, 0C...
for (int i = 0; i < hex.length() - 1; i += 2) {
String tempInHex = hex.substring(i, (i + 2));
// convert hex to decimal
int decimal = Integer.parseInt(tempInHex, 16);
// convert the decimal to char
result.append((char) decimal);
}
return result.toString();
}
public static void main(String[] args) {
String input = "a";
// String input = "java";
System.out.println("input : " + input);
String hex = convertStringToHex(input);
System.out.println("hex : " + hex);
String result = convertHexToString(hex);
System.out.println("result : " + result);
}
}
Output
input : a
hex : 61
result : a
For input java
input : java
hex : 6a617661
result : java
3. Bitwise
This bitwise conversion is similar to the Apache Commons Codec source code, read comment for self-explanatory.
HexUtils3.java
package com.favtuts.converter;
import java.nio.charset.StandardCharsets;
public class HexUtils3 {
private static final char[] HEX_UPPER = "0123456789ABCDEF".toCharArray();
private static final char[] HEX_LOWER = "0123456789abcdef".toCharArray();
public static void main(String[] args) {
String input = "java";
System.out.println("input : " + input);
String hex = convertStringToHex(input, false);
System.out.println("hex : " + hex);
}
public static String convertStringToHex(String str, boolean lowercase) {
char[] HEX_ARRAY = lowercase ? HEX_LOWER : HEX_UPPER;
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
// two chars form the hex value.
char[] hex = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
// 1 byte = 8 bits,
// upper 4 bits is the first half of hex
// lower 4 bits is the second half of hex
// combine both and we will get the hex value, 0A, 0B, 0C
int v = bytes[j] & 0xFF; // byte widened to int, need mask 0xff
// prevent sign extension for negative number
hex[j * 2] = HEX_ARRAY[v >>> 4]; // get upper 4 bits
hex[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; // get lower 4 bits
}
return new String(hex);
}
}
Output
input : java
hex : 6A617661
Note
If you are confused, picks Apache Commons Codec for the safe bet.
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-misc