ByteCode representation to byte []

advertisements

if I do something like this :

img.getImageBytes(); /*returns byte[] from image */

How can I do the inverse with the string that represents that byte[] ?


I don't know how you are printing the byte array. But assuming you are using it's toString() method or Arrays.toString() method.

Then you take the string representation of the byte[], strip off leading [ and rearing ] and split it by , into a String[]. Now create a new byte[] with the same size of the String[]. Then iterate over the String[] and convert each element and add to the byte[]. Example

    byte[] b = {1, 2, 3, 4, 5}; //Initial byte array also can be gotten from any other source
    String s = b.toString(); //[1, 2, 3, 4, 5]

    String[] sa = s.substring(1, s.length() - 1).split(",");
    byte[] ba = new byte[sa.length];

    for(int i = 0; i < ba.length; i++) {
        ba[i] = Byte.valueOf(sa[i].trim());
    }

    //Now ba should contain 1, 2, 3, 4, 5