How to convert a binary representation of a string into byte in Java?

32,693

Solution 1

You can use Byte.parseByte() with a radix of 2:

byte b = Byte.parseByte(str, 2);

Using your example:

System.out.println(Byte.parseByte("01100110", 2));
102

Solution 2

You can parse it to an integer in base 2, and convert to a byte array. In your example you've got 16 bits you can also use short.

short a = Short.parseShort(b, 2);
ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a);

byte[] array = bytes.array();

Just in case if you need it for a Very Big String.

String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();
Share:
32,693
westberg
Author by

westberg

Updated on December 29, 2020

Comments

  • westberg
    westberg over 3 years

    as the title says, how do I do it? Its easy to convert from string -> byte -> string binary, But how do I convert back? Below is a example. The output is : 'f' to binary: 01100110 294984

    I read somewhere that I could use the Integer.parseInt but clearly that is not the case :( Or am I doing something wrong?

    Thanks, :)

    public class main{
        public static void main(String[] args) {
    
             String s = "f";
              byte[] bytes = s.getBytes();
              StringBuilder binary = new StringBuilder();
              for (byte b : bytes)
              {
                 int val = b;
                 for (int i = 0; i < 8; i++)
                 {
                    binary.append((val & 128) == 0 ? 0 : 1);
                    val <<= 1;
                 }
                 binary.append(' ');
              }
              System.out.println("'" + s + "' to binary: " + binary);
    
            System.out.println(Integer.parseInt("01100110", 2));
        }
    }