Nick Nick - 2 years ago 112
Java Question

Binary to text in Java

I have a String with binary data in it (1110100) I want to get the text out so I can print it (1110100 would print "t"). I tried this, it is similar to what I used to transform my text to binary but it's not working at all:

public static String toText(String info)throws UnsupportedEncodingException{
byte[] encoded = info.getBytes();
String text = new String(encoded, "UTF-8");
System.out.println("print: "+text);
return text;

Any corrections or suggestions would be much appreciated.


Answer Source

You can use Integer.parseInt with a radix of 2 (binary) to convert the binary string to an integer:

int charCode = Integer.parseInt(info, 2);

Then if you want the corresponding character as a string:

String str = new Character((char)charCode).toString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download