14

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?

Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82
Ryan Jackman
  • 780
  • 2
  • 8
  • 24

3 Answers3

26

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();
Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
  • 6
    What if the String contains too many bits that it can't be hold even in a `long` variable? – Luiggi Mendoza Jul 18 '13 at 15:14
  • If the string is too big, then you'll get a `NumberFormatException`. I'm making assumptions that it's less than 32 characters for this small example. – Jeff Foster Jul 18 '13 at 15:17
  • Then this is not a bullet-proof solution. Is there any with simple code or it involves manual working on the String contents? – Luiggi Mendoza Jul 18 '13 at 15:19
  • 3
    I'm not sure this could get much simple? If `b` is in an invalid format a `NumberFormatException` will be thrown and it's up to the callee to handle the error. Open to suggestions on how to improve this, but I think this is enough of an answer to illustrate the point. – Jeff Foster Jul 18 '13 at 15:23
  • @LuiggiMendoza using `BigInteger` as the other answer suggested will take care of that issue. – Steve P. Jul 18 '13 at 15:29
  • Thank you, this worked well. I should have been more clear though, I split the string every 8 characters so I only needed to loop through the split string and add it to the byte[] array. – Ryan Jackman Jul 18 '13 at 15:30
25

Another simple approach is:

String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();
Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82
  • 4
    it cannot parse "1110100001101001" – Evgeniy Dorofeev Aug 29 '13 at 07:03
  • 2
    See http://stackoverflow.com/questions/24158629/biginteger-tobytearray-returns-purposeful-leading-zeros You might have some sign issues. – will Jun 02 '16 at 18:59
  • When I'm displaying byte[] fspec = new BigInteger("10000000", 2).toByteArray();, it shows [B@3b22cdd0 instead of expected value - why? – Line Jun 28 '17 at 13:25
  • 2
    @Line Because you're displaying it wrong. See [What's the simplest way to print a Java array?](https://stackoverflow.com/q/409784/5221149) – Andreas Mar 26 '18 at 16:20
2

Assuming that your binary String can be divided by 8 without getting a rest you can use following method:

/**
 * 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;
}

Don't forget to add the guava lib to your dependecies.

In Android you should add to app gradle:

compile group: 'com.google.guava', name: 'guava', version: '19.0'

And add this into project gradle:

allprojects {
    repositories {
        mavenCentral()
    }
}

Update 1

This post contains a solution without using Guava Lib.

Community
  • 1
  • 1
lidox
  • 1,901
  • 3
  • 21
  • 40