Java convert hex string to java: char[] (C) to byte[] (JAVA)

c, java

Solution

If you actually want to convert the given string to a `byte[]` (though this seems like a strange requirement)...

String hexString = "0x02, 0x04, 0xF3, 0xFC, 0xFF, 0x06, 0x00, 0xF7, 0x00, 0x00, 0x09, 0xFD, 0xFD, 0x00, 0x03, 0x0A, 0xFD, 0x02, 0xFD, 0x08, 0x08, 0x00, 0x01, 0xFD";
String[] split = hexString.split(", ");
byte[] arr = new byte[split.length];
for (int i = 0; i < split.length; i++)
{
   arr[i] = (byte)Short.parseShort(split[i].substring(2), 16);
}
System.out.println(Arrays.toString(arr));

We need to use `parseShort` instead of `parseByte` because trying to parse something like `0xF3` with `parseByte` causes `NumberFormatException: Value out of range`.

Prints:

[2, 4, -13, -4, -1, 6, 0, -9, 0, 0, 9, -3, -3, 0, 3, 10, -3, 2, -3, 8, 8, 0, 1, -3]

Problem

How to convert hex string in java that keep the same values. In C i have: ``` char tab[24] = { 0x02, 0x04, 0xF3, 0xFC, 0xFF, 0x06, 0x00, 0xF7, 0x00, 0x00, 0x09, 0xFD, 0xFD, 0x00, 0x03, 0x0A, 0xFD, 0x02, 0xFD, 0x08, 0x08, 0x00, 0x01, 0xFD }; ``` And i copy to java like a string; ``` String hexString = "0x02, 0x04, 0xF3, 0xFC, 0xFF, 0x06, 0x00, 0xF7, 0x00, 0x00, 0x09, 0xFD, 0xFD, 0x00, 0x03, 0x0A, 0xFD, 0x02, 0xFD, 0x08, 0x08, 0x00, 0x01, 0xFD"; ``` Now i want to convert in byte[], i find some ways how to do it but it looks like i do not convert in right format. SOLVED ``` String[] split = hexString.split(", "); byte[] arr = new byte[split.length]; for (int i = 0; i < split.length; i++) { arr[i] = (byte)(short)Short.decode(split[i]); } ```

Original source