Date: 2015jul17
Updated: 2025sep20
Language: Java
Keywords: hexadecimal
Q. Java: Convert a hex string into binary data
A. Here is a function called hexStringToBinaryData() shown in a full example:
import java.util.ArrayList;
class Demo {
static ArrayList<Byte> hexStringToBinaryData(final String hex) {
ArrayList<Byte> out = new ArrayList<Byte>();
for (int i = 0; i < hex.length(); i += 2) {
out.add((byte) Integer.parseInt(hex.substring(i, i + 2), 16));
}
return out;
}
public static void main(String []args) {
ArrayList<Byte> out = hexStringToBinaryData("10203040"); // Example data
System.out.println("out=" + out);
}
}
Output:
out=[16, 32, 48, 64]
Since 0x10 is 16 decimal, 0x20 is 32 decimal, etc