2013-07-18 115 views
6

我有一串1和零,我想要转换为一个字节数组。将二进制字符串转换为字节数组

例如String b = "0110100001101001"怎样才能将它转换为长度为2的byte[]

+0

为什么长度2? –

+3

@kocko他有16位... –

+0

根据字符串b,你想要一个byte []长度为2,'104'在位置0,'105'在位置1? –

回答

21

将其解析为基数为2的整数,然后转换为字节数组。事实上,由于你有16位,现在是时候打破罕见的short

short a = Short.parseShort(b, 2); 
ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a); 

byte[] array = bytes.array(); 
+3

如果字符串中包含的位太多,即使在一个“长”变量中也不能保持? –

+0

这太酷了!我不知道,谢谢! :) –

+0

如果字符串太大,那么你会得到一个'NumberFormatException'。我假设这个小例子少于32个字符。 –

12

另一种简单的方法是:

String b = "0110100001101001"; 
byte[] bval = new BigInteger(b, 2).toByteArray(); 
+1

它无法解析“1110100001101001” –

+0

请参阅http://stackoverflow.com/questions/24158629/biginteger-tobytearray-returns-purposeful-leading-zeros 您可能有一些迹象问题。 – will

+0

当我显示byte [] fspec = new BigInteger(“10000000”,2).toByteArray();,它显示[B @ 3b22cdd0而不是期望值 - 为什么? – Line

0

假设你的二进制字符串可以由8个分没有得到休息,你可以使用下面的方法:

/** 
* Get an byte array by binary string 
* @param binaryString the string representing a byte 
* @return an byte array 
*/ 
public static byte[] getByteByString(String binaryString){ 
    Iterable iterable = Splitter.fixedLength(8).split(binaryString); 
    byte[] ret = new byte[Iterables.size(iterable) ]; 
    Iterator iterator = iterable.iterator(); 
    int i = 0; 
    while (iterator.hasNext()) { 
     Integer byteAsInt = Integer.parseInt(iterator.next().toString(), 2); 
     ret[i] = byteAsInt.byteValue(); 
     i++; 
    } 
    return ret; 
} 

不要忘记将guava lib添加到您的依赖关系。

在Android中,你应该添加到应用程序的gradle产出:

compile group: 'com.google.guava', name: 'guava', version: '19.0' 

并添加到项目中的gradle产出这样的:

allprojects { 
    repositories { 
     mavenCentral() 
    } 
} 

更新1

This post contains的解决方案,而无需使用番石榴库。

相关问题