Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of strings to array of bytes

I have a String array, each array element is a hex string that consist of 2 chars.

For example the array could be:

String a = {"aa","ff","00",.....}

How can I convert this array of strings to an array of bytes in Java?

like image 998
user1077980 Avatar asked Dec 31 '11 15:12

user1077980


1 Answers

If you want to parse unsigned byte hex-strings, use

byte[] b = new byte[a.length()];

for (int i=0; i<a.length(); i++) {
    b[i] = (byte) Short.parseShort(a[i], 16);
}

"ff" will be parsed to -1, as per two's compliment.

If you want "ff" to parse to 255 (higher than a java byte can hold) you will need to use shorts

short[] b = new short[a.length()];

for (int i=0; i<a.length(); i++) {
    b[i] = Short.parseShort(a[i], 16);
}
like image 62
Aaron J Lang Avatar answered Oct 14 '22 19:10

Aaron J Lang