Akshay Sharma
Akshay Sharma

Reputation: 15

Convert ArrayList String value to byte array

I have an "Arraylist" of String format with exact values of byte array like

{-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 84, 0, 0, 0, 84, 8, 6, 0, 0}

I have want to convert it back to byte array which looks the same like

{-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 84, 0, 0, 0, 84, 8, 6, 0, 0}

But i cant find a method to do this I want to this so i can decode an Image out the byte array but no luck

I tried to use this method where "yolo" is my arraylist but the output bytearray has differnet values why ?

ByteArrayOutputStream lp = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(lp);

for (String element : yolo) 
     {
       try
       {
           out.writeUTF(element);
       }catch(IOException e)
          {
            e.printStackTrace();
          }
    }

    byte myimage[] = lp.toByteArray(); 

Upvotes: 1

Views: 4067

Answers (2)

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

Don't use ByteArrayOutputStream it is much, much slower than an ordinary byte array. Also foreach is slower than a normal for loop in an ArrayList, this is the optimized solution for you problem

int size = yolo.size();
byte[] byteArray = new byte[size]; 
for (int i = 0; i < size ; ++i)
{
    byteArray[i] = Byte.valueOf(yolo.get(i));
}

Upvotes: 0

jean d&#39;arme
jean d&#39;arme

Reputation: 4343

Try using loop to go through every position and use Byte.valueof(yolo[position]) for each position in Your array and You should have it.

Upvotes: 1

Related Questions