How to convert hex string to Java string?
Solution 1:
Using Hex
in Apache Commons:
String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Solution 2:
byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);
Solution 3:
You can go from String (hex)
to byte array
to String as UTF-8(?)
. Make sure your hex string does not have leading spaces and stuff.
public static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
Usage:
String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);
Solution 4:
First of all read in the data, then convert it to byte array:
byte b = Byte.parseByte(str, 16);
and then use String
constructor:
new String(byte[] bytes)
or if the charset is not system default then:
new String(byte[] bytes, String charsetName)
Solution 5:
Try the following code:
public static byte[] decode(String hex){
String[] list=hex.split("(?<=\\G.{2})");
ByteBuffer buffer= ByteBuffer.allocate(list.length);
System.out.println(list.length);
for(String str: list)
buffer.put(Byte.parseByte(str,16));
return buffer.array();
}
To convert to String just create a new String with the byte[] returned by the decode method.