[Solved] How to convert an array of numeric values as strings to an array of bytes?


Do use Byte.parseByte(String) to do this:

public static byte[] toByteArray(String[] arr) {
    byte[] res = new byte[arr.length];

    for (int i = 0; i < arr.length; i++)
        res[i] = Byte.parseByte(arr[i]);

    return res;
}

P.S.
In Java byte values are [-128; 128). Therefore "128" will throw java.lang.NumberFormatException: Value out of range. Value:"128" Radix:10. The you have to decide what you want to do with those value: throw exception, because of invalid use data; or cast it to the closest byte value, like "128" -> 127; or even ignore such values. Then this code could look like this:

public static byte[] toByteArray(String[] arr) {
    byte[] res = new byte[arr.length];

    for (int i = 0; i < arr.length; i++) {
        try {
            res[i] = Byte.parseByte(arr[i]);    
        } catch(Exception e) {
            res[i] = // TODO action for incorrect value
        }
    }

    return res;
}

4

solved How to convert an array of numeric values as strings to an array of bytes?