如何将大型二进制String转换为字节数组java?

时间:2014-05-14 20:04:06

标签: java string binary bytearray

我有一个大的二进制字符串“101101110 ...”,我试图将它存储到一个字节数组中。这样做的最佳方式是什么?

假设我有largeString =“0100111010111011011000000001000110101”

我正在寻找的结果:

[78,187,96,17,21]

01001110 10111011 01100000 00010001 10101

我尝试了什么:

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

然而它没有给我我想要的结果......

3 个答案:

答案 0 :(得分:6)

如果你想要一个实际的数组,你可以轻松地构建一个可以调用toAray的ArrayList;

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]

答案 1 :(得分:0)

循环播放。将字符串拆分为8个字符的块并单独转换它们。在“伪代码”中,它类似于:

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

答案 2 :(得分:0)

假设您的二进制字符串模块8等于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;
    }
}