Java Convert Hex String to Byte Array
Tags: HexUtils
In this Java tutorial, we learn how to implement a Java utility method to convert a hex String into byte array in Java programming language.
How to convert hex String to byte array in Java
At this first step, create a new Java class named HexUtils, and a new static method named fromHex(String hex) to convert a hex String into byte array as the following Java code.
HexUtils.java
public class HexUtils {
/**
* this method to convert a hex String to byte array
* @param hex the input hex String
* @return the byte array
*/
public static byte[] fromHex(String hex) {
byte[] result = new byte[(hex.length() + 1) / 2];
int stringOffset = 0;
String hexNumber = null;
int byteOffset = 0;
while(stringOffset < hex.length()) {
hexNumber = hex.substring(stringOffset, stringOffset + 2);
stringOffset += 2;
result[byteOffset] = (byte) Integer.parseInt(hexNumber, 16);
byteOffset++;
}
return result;
}
}
In the following example Java code, we learn how to use the above HexUtils.fromHex(String hex) static method in Java program.
HexUtilsFromHexExample.java
import java.util.Arrays;
public class HexUtilsFromHexExample {
public static void main(String... args) {
String hex = "53696d706c6520536f6c7574696f6e";
// Convert Hex String to Byte Array
byte[] data = HexUtils.fromHex(hex);
System.out.println("Hex String: " + hex);
System.out.println("Byte array: " + Arrays.toString(data));
System.out.println("String value from bytes: " + new String(data));
}
}
Hex String: 53696d706c6520536f6c7574696f6e
Byte array: [83, 105, 109, 112, 108, 101, 32, 83, 111, 108, 117, 116, 105, 111, 110]
String value from bytes: Simple Solution
Happy Coding 😊
Related Articles
Java Convert Byte Array to Hex String
How to Convert Object to Map in Java