Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Why of length 2 ? –  kocko Jul 18 '13 at 15:11
1  
@kocko he has 16 bits... –  Heuster Jul 18 '13 at 15:13
    
Based off of string b, you want a byte[] length 2 with 104 in position 0, and 105 in position 1? –  Saviour Self Jul 18 '13 at 15:18
    
possible duplicate of convert a string to byte array –  Shashi Jul 25 '13 at 7:37
add comment

2 Answers

up vote 12 down vote accepted

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();
share|improve this answer
    
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
    
This is very cool! I didn't know it, thanks! :) –  kocko 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
2  
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
show 2 more comments

Another simple approach is:

String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();
share|improve this answer
    
it cannot parse "1110100001101001" –  Evgeniy Dorofeev Aug 29 '13 at 7:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.