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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With