Fishstick Fishstick - 1 month ago 16
Java Question

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
of length 2?


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();