Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary string to byte array

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

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

like image 955
Ryan Jackman Avatar asked Jul 18 '13 15:07

Ryan Jackman


People also ask

Can we convert String to byte array in Java?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

Is byte array same as binary?

Byte arrays mostly contain binary data such as an image. If the byte array that you are trying to convert to String contains binary data, then none of the text encodings (UTF_8 etc.) will work.

Can byte array be converted to String?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

What is a byte array?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..


2 Answers

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();
like image 114
Jeff Foster Avatar answered Sep 29 '22 21:09

Jeff Foster


Another simple approach is:

String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();
like image 34
Shreyos Adikari Avatar answered Sep 29 '22 22:09

Shreyos Adikari