Lynct Lynct - 6 months ago 37
Java Question

How do I convert a large binary String to byte array java?

I have a large binary string "101101110...", and I am trying to store it into a byte array. what is the best way of doing it?

Lets say I have largeString = "0100111010111011011000000001000110101"

Result that I'm looking for:

[78, 187, 96, 17, 21]

01001110 10111011 01100000 00010001 10101

What i've tried:

byte[] b= new BigInteger(largeString,2).toByteArray();

however it did not give me the result I'm looking for...


You can easily build an arrayList on which you can call toArray if you want an actual array;

ArrayList<Integer> arrayList = new ArrayList<>();

for(String str : largeString.split("(?<=\\G.{8})"))
    arrayList.add(Integer.parseInt(str, 2));

System.out.println(arrayList);  // Outputs [78, 187, 96, 17, 21]