将二进制字符串转换为字节数组
我有一串1和0,我想转换为字节数组。
例如, String b = "0110100001101001"
如何将其转换为长度为2的byte[]
?
将其解析为基数为2的整数,然后转换为字节数组。 实际上,由于你有16位,所以是时候打破很少使用的short
。
short a = Short.parseShort(b, 2); ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a); byte[] array = bytes.array();
另一个简单的方法是:
String b = "0110100001101001"; byte[] bval = new BigInteger(b, 2).toByteArray();
假设您的二进制字符串可以除以8而不rest,您可以使用以下方法:
/** * 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; }
不要忘记将番石榴lib添加到您的家属。
在Android中,您应该添加到app gradle:
compile group: 'com.google.guava', name: 'guava', version: '19.0'
并将其添加到项目gradle中:
allprojects { repositories { mavenCentral() } }
更新1
这篇文章包含一个不使用Guava Lib的解决方案。