Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c

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]);
}
like image 654
rikkima Avatar asked Mar 27 '26 01:03

rikkima


2 Answers

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]
like image 105
Bernhard Barker Avatar answered Mar 29 '26 14:03

Bernhard Barker


What you have in C would be this in Java:

byte[] tab = { 0x02, 0x04, (byte) 0xF3, (byte) 0xFC, (byte) 0xFF, 0x06, 
               0x00, (byte) 0xF7, 0x00, 0x00, 0x09, (byte) 0xFD, (byte) 0xFD, 
               0x00, 0x03, 0x0A, (byte) 0xFD, 0x02, (byte) 0xFD, 0x08, 
               0x08, 0x00, 0x01, (byte) 0xFD };

Note that instead of char you use byte, and that values that are outside of the allowed range for byte such as 0xFD need an explicit cast. And you don't include the array length in the declaration.


Update: To not add casts manually you can declare the data of a wider type (like int or short) and then loop over it:

int[] temp = { ... };
byte[] tab = new byte[temp.length];
for (int i = 0; i<temp.length; i++) tab[i]=(byte)temp[i];

A better solution would be loading the data from an external file though. Big array literals are not encoded into class files in a compact way like C compilers encode big array literals.

like image 29
Joni Avatar answered Mar 29 '26 14:03

Joni