Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 481
Lynct Avatar asked Jul 30 '26 12:07

Lynct


2 Answers

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

List<Integer> list = new ArrayList<>();

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

System.out.println(list);  // Outputs [78, 187, 96, 17, 21]
like image 142
Joachim Isaksson Avatar answered Aug 01 '26 01:08

Joachim Isaksson


Assuming that your binary string module 8 equals 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;
    }
}
like image 27
lidox Avatar answered Aug 01 '26 01:08

lidox