Convert string array to byte array

I have a string array, each element of the array is a hexString consisting of 2 characters.

For example, an array could be:

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

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

+5
source share
4 answers

If you want to parse unsigned hexadecimal 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, according to two compliments .

If you want ff to parse up to 255 (higher than Java bytes can be stored), 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);
}
+4
source

Scroll through the array and convert each line to byte using

byte b = (byte) (Integer.parseInt(theHexaString, 16)); 

Byte.parseByte() .

+3

If I understand correctly, do you need a representation of the bytes of the concatenated strings? Sort of:

public byte[] getBytes(String[] array) {
    StringBuilder builder = new StringBuilder();
    for(String s: array) {
       builder.append(s);
    }
    return builder.toString().getBytes();
}
0
source

You should take a look at ByteArrayOutputStream .

You can then iterate over each row and use the Byte.parseByte () method . You can add it to ByteArrayOutputStream using the write method .

Once you convert all the strings, you can use the ByteArrayOutputStream toByteArray () method .

0
source

All Articles