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
-
1Why do you need it? You already have the equivalent string.Runcorn– Runcorn2014年08月05日 05:54:58 +00:00Commented Aug 5, 2014 at 5:54
-
I am working on project in final year so it is important for me.Compression– Compression2014年08月05日 10:20:59 +00:00Commented Aug 5, 2014 at 10:20
2 Answers 2
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
Compression
dude what do you mean by "\\s"?
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
Compression
System.out.print((char)Byte.parseByte(c,2)); what does 2nd parameter says ??
AdityaKeyal
The 2nd parameter (2) says that the number is in binary format hence the base radix = 2.
lang-java