javastringbinarybinarystream

How to convert a binary string back into a string


Here is what i am trying to do. I have a string :

String s="ch"

I convert it into a binary string in the following way

char ar[]=s.toCharArray();
StringBuilder sb= new StringBuilder("00"); /* i am appending to extra zeros because                        
                                                  when i convert "ch" to binary string it   
                                                 consists of 14 characters(0s and 1s) and i                 
                                               need them to be a multiple of 8, so i add 2 
                                                0s to make it 16)*/
String wm="  ";
for(char c:ar)
{
    wm=Integer.toBinaryString((int)c);
    sb.append(wm);
}

Now i want to convert this binary string back into character...such that i get back "ch" as the output. Can anyone help?


Solution

  • You can parse a binary string to an int with Integer#parseInt(String s, int radix), and then cast it to a char:

    char result = (char) Integer.parseInt(s, 2);
    

    EDIT Your string will look like this:

    0011000111101000
    00<--c--><--h-->
    

    To get c and h separately you need to split the String. Try using String#substring() to get the parts of the string belonging to the different letters. All lowercase letters are 7 digits long, so it shouldn't be too difficult.