将二进制字符串转换为字节数组 [英] Convert binary string to byte array
本文介绍了将二进制字符串转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由 1 和 0 组成的字符串,我想将其转换为字节数组.
I have a string of ones and zeros that I want to convert to an array of bytes.
例如 String b = "0110100001101001"
如何将其转换为长度为 2 的 byte[]
?
For example String b = "0110100001101001"
How can I convert this to a byte[]
of length 2?
推荐答案
将其解析为基数为 2 的整数,然后转换为字节数组.事实上,既然你有 16 位,是时候打破很少使用的short
.
Parse it to an integer in base 2, then convert to a byte array. In fact, since you've got 16 bits it's time to break out the rarely used short
.
short a = Short.parseShort(b, 2);
ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a);
byte[] array = bytes.array();
这篇关于将二进制字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文