Published 19 Sep, 2022

Java - Binary to text in Java

Category Java
Modified : Oct 03, 2022
108

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.

Thanks!

Answers

There are 4 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as String, Java, Encoding, Utf 8, Nsstringencoding. These have been categorized in sections for a clear and precise explanation.

75

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();

40

I know the OP stated that their binary was in a String format but for the sake of completeness I thought I would add a solution to convert directly from a byte[] to an alphabetic String representation.

As casablanca stated you basically need to obtain the numerical representation of the alphabetic character. If you are trying to convert anything longer than a single character it will probably come as a byte[] and instead of converting that to a string and then using a for loop to append the characters of each byte you can use ByteBuffer and CharBuffer to do the lifting for you:

public static String bytesToAlphabeticString(byte[] bytes) {
    CharBuffer cb = ByteBuffer.wrap(bytes).asCharBuffer();
    return cb.toString();
}

N.B. Uses UTF char set

Alternatively using the String constructor:

String text = new String(bytes, 0, bytes.length, "ASCII");

33

Look at the parseInt function. You may also need a cast and the Character.toString function.


25

Here is the answer.

private String[] splitByNumber(String s, int size) {
    return s.split("(?<=\\G.{"+size+"})");
}