How to convert a large binary string to a java byte array?

I have a large binary string "101101110 ..." and I'm trying to store it in an array of bytes. What is the best way to do this?

Let's say I have largeString = "0100111010111011011000000001000110101"

The result I'm looking for:

[78, 187, 96, 17, 21]

01001110 10111011 01100000 00010001 10101

What I tried:

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

however, he did not give me the result that I am looking for ...

+2
source share
3 answers

You can easily create an array of List, by which you can call toArray if you want to have a real 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] 
+6
source

Do it in a loop. Divide the string into 8-character fragments and convert them separately. In the "pseudo-code" it is something like:

 byte[] result = new byte[subs.size()]; int i = 0; int j = 0; while(i+8 <= s.length){ result[j] = new Byte.valueOf(largeString.substring(i, i+8), 2); i+=8; j++; } result[j] = new Byte.valueOf(largeString.substring(i, largeString.length)); 
0
source

Assuming your binary string module 8 is 0 binString.lenght()%8==0

  /** * Get an byte array by binary string * @param binaryString the string representing a byte * @return an byte array */ public static byte[] getByteByString(String binaryString) { int splitSize = 8; if(binaryString.length() % splitSize == 0){ int index = 0; int position = 0; byte[] resultByteArray = new byte[binaryString.length()/splitSize]; StringBuilder text = new StringBuilder(binaryString); while (index < text.length()) { String binaryStringChunk = text.substring(index, Math.min(index + splitSize, text.length())); Integer byteAsInt = Integer.parseInt(binaryStringChunk, 2); resultByteArray[position] = byteAsInt.byteValue(); index += splitSize; position ++; } return resultByteArray; } else{ System.out.println("Cannot convert binary string to byte[], because of the input length. '" +binaryString+"' % 8 != 0"); return null; } } 
0
source

Source: https://habr.com/ru/post/949759/


All Articles