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);
asked Aug 5, 2014 at 5:46
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);
answered Aug 5, 2014 at 7:48
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

answered Aug 5, 2014 at 6:00

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.