java将二进制字符串转换为字节数组 5 月 Questions & Answers 38272 我有一个由1和0组成的字符串,我想将其转换为一个字节数组 例如String b = "0110100001101001"如何将其转换为长度为2的byte[]
# 1 楼答案 将其解析为基数为2的整数,然后转换为字节数组。事实上,既然你已经有了16位,现在是时候打破很少使用的short了 short a = Short.parseShort(b, 2); ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a); byte[] array = bytes.array();
# 3 楼答案 假设二进制字符串可以被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不使用番石榴酱的溶液
# 1 楼答案
将其解析为基数为2的整数,然后转换为字节数组。事实上,既然你已经有了16位,现在是时候打破很少使用的
short
了# 2 楼答案
另一个简单的方法是:
# 3 楼答案
假设二进制字符串可以被8除而不需要休息,则可以使用以下方法:
别忘了将guava lib添加到依赖项中
在Android系统中,您应该将以下内容添加到应用程序gradle中:
并将此添加到gradle项目中:
更新1
This post contains不使用番石榴酱的溶液