转换二进制字符串字节数组 [英] Convert binary string to byte array

查看:156
本文介绍了转换二进制字符串字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一和零,我要转换为字节数组的字符串。

I have a string of ones and zeros that I want to convert to an array of bytes.

举例字符串B =0110100001101001我怎样才能将其转换为一个字节[] 长度为2 ?

For example String b = "0110100001101001" How can I convert this to a byte[] of length 2?

推荐答案

解析它的一个整数基地2个,然后将其转换为字节数组。事实上,因为你已经拿到了16位,是时候打出来的很少使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆