简体   繁体   中英

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;

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]

Do it in a loop. Split the string at 8-character chunks and convert them separately. In "pseudocode" it's 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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM