简体   繁体   中英

Convert binary string to byte-Array in Java

I have a binary string and I want to split it into chunks of length 8 and then store the corresponding bytes in a byte-Array. For example, the string "0000000011111111" should be convertert to {-128, 127}. So far, I wrote the following function:

public static byte[] splitBinary(String binaryString) throws ConversionException {

    if (binaryString.length()%8 != 0) {
        throw new ConversionException();
    }

    byte[] result = new byte[binaryString.length()/8];

    while (i < result.length) {
        result[i] = (byte) (Integer.parseInt(binaryString.substring(i, i+8), 2)-128);
        i+=8;
    }
    return result;
} 

But this results in {-128, 0}. How can I achieve the desired functionality?

Your splitting routine is wrong.

increasing i by 1 just moves your window one charachter to the right, not two, resulting in die Strings 00000000 and 00000001 to be read.

I refer to result's size, it may smaller than size of binaryString , but in binaryString.substring(i, i+8) and i+=8 ; you use as size of binaryString . So change them to binaryString.substring(i*8, i*8+8) and i++ .

I changed the function in the following way and now it works as expected (after correcting my expectations ;)). Thank you all!

public static byte[] splitBinaryStringToByteArray(String binaryString) throws ConversionException {

    if (binaryString.length()%8 != 0) {
        throw new ConversionException();
    }

    byte[] result = new byte[binaryString.length()/8];

    int i =0;int j=0;
    while (i < binaryString.length()) {
        System.out.println("Substring: " + binaryString.substring(i, i+8));
        result[j] =((byte)Integer.parseInt((binaryString.substring(i, i+8)), 2));
        j++;
        i+=8;
    }
    return result;
}

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