2

I convert String to binary using following code. Now i want to convert it back to string then how can i do it.

 String s = "Milind";
 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);
2
  • 1
    Why do you need it? You already have the equivalent string. Commented Aug 5, 2014 at 5:54
  • I am working on project in final year so it is important for me. Commented Aug 5, 2014 at 10:20

2 Answers 2

1

You Can Try This:

String[] singleBinaryArray = binary.toString().split("\\s");
String finalResult = "";
for (String string : singleBinaryArray) {
Character c = (char) Integer.parseInt(string, 2);
    finalResult += c.toString();
}
System.out.println("String " + finalResult);
Sign up to request clarification or add additional context in comments.

1 Comment

dude what do you mean by "\\s"?
0

The solution you are looking for is as below:

 String[] bytesStr = binary.toString().split(" ");

            for(String c :  bytesStr){
                System.out.print((char)Byte.parseByte(c,2));    
            }

The "binary" value you have is in reality the binary in string format. So convert it to a byte by using parseByte with a radix (base) of 2.

The above program prints Milind

2 Comments

System.out.print((char)Byte.parseByte(c,2)); what does 2nd parameter says ??
The 2nd parameter (2) says that the number is in binary format hence the base radix = 2.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.