将ArrayList String值转换为byte数组

时间:2021-02-09 16:09:56

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

我有一个String格式的“Arraylist”,其字节数组的精确值就像

{-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}

{-119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,80,0,0,04, 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}

{-119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,80,0,0,04, 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 ?

我尝试使用这种方法,其中“yolo”是我的arraylist但输出bytearray有不同的值为什么?

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(); 

2 个解决方案

#1


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.

尝试使用循环遍历每个位置并对阵列中的每个位置使用Byte.valueof(yolo [position]),你应该拥有它。

#2


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

不要使用ByteArrayOutputStream它比普通的字节数组慢得多。此外,foreach比ArrayList中的正常for循环慢,这是针对您问题的优化解决方案

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

#1


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.

尝试使用循环遍历每个位置并对阵列中的每个位置使用Byte.valueof(yolo [position]),你应该拥有它。

#2


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

不要使用ByteArrayOutputStream它比普通的字节数组慢得多。此外,foreach比ArrayList中的正常for循环慢,这是针对您问题的优化解决方案

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