Queries and Questions

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=newStringBuilder("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?

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:

001100011110100000<--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.

 
Advertisements

Constructive and genuine appreciation and/or criticism most welcome

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s