1

As the title says, I have to convert a binary string to byte format. My binary string contains only 6 bit data. I need to convert this 6 bit binary string to byte values

binary string

String s1 =  "111011";
String s2 =  "111000";
String s3 =  "000000";
String s4 =  "111000";
String s5 =  "110111";
Arya
  • 1,729
  • 3
  • 17
  • 35
  • 4
    Possible duplicate of [Convert binary string to byte array](http://stackoverflow.com/questions/17727310/convert-binary-string-to-byte-array) – Rami Dec 01 '15 at 10:38
  • i hope i could help with my answer! if there are anymore questions feel free to ask! – ParkerHalo Dec 01 '15 at 12:32

3 Answers3

0

Try using Byte.parseByte() with a radix of 2 - Javadoc:

byte b = Byte.parseByte(s1, 2);
Iffo
  • 353
  • 7
  • 18
  • I have tried this. but my binary string have only 6 bit data. I am getting an error java.lang.NumberFormatException: Value out of range for byte: "111011" – Arya Dec 01 '15 at 10:39
  • @Arya try using `StringUtils.leftPad(s1, 8, '0')` – Iffo Dec 01 '15 at 11:27
0

You could do it "manually" by converting it yourself

byte b = 0, pot = 1;
for (int i = 5; i >= 0; i--) {
    // -48: the character '0' is No. 48 in ASCII table,
    // so substracting 48 from it will result in the int value 0!
    b += (str.charAt(i)-48) * pot;
    pot <<= 1;    // equals pot *= 2 (to create the multiples of 2 (1,2,3,8,16,32)
}

This will multiply the bits with (1, 2, 4, 8, 16, 32) in order to determine the resulting decimal number.

Another possibility would be to really manually calculate the 6 binary digits into a decimal value:

byte b = (byte)
    ((str.charAt(5) - '0') * 1 +
    (str.charAt(4) - '0') * 2 + 
    (str.charAt(3) - '0') * 4 + 
    (str.charAt(2) - '0') * 8 + 
    (str.charAt(1) - '0') * 16 + 
    (str.charAt(0) - '0') * 32);
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
0

Do you need an actual byte, or are you looking for a int?

String s = "101";
System.out.println(Integer.parseInt(s,2));
Sean
  • 126
  • 1
  • 4