Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks!

like image 418
Nick Avatar asked Nov 18 '10 04:11

Nick


People also ask

How do you write binary in Java?

Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value.

What is a binary string Java?

A binary string is a sequence of bytes. Unlike a character string which usually contains text data, a binary string is used to hold non-traditional data such as pictures. The length of a binary string is the number of bytes in the sequence. A binary string has a CCSID of 65535.

How do you convert a string to binary in Java?

toBinaryString() method in Java converts int to binary string. Let's say the following are our integer values. int val1 = 9; int val2 = 20; int val3 = 2; Convert the above int values to binary string.


3 Answers

This is my one (Working fine on Java 8):

String input = "01110100"; // Binary input as String
StringBuilder sb = new StringBuilder(); // Some place to store the chars

Arrays.stream( // Create a Stream
    input.split("(?<=\\G.{8})") // Splits the input string into 8-char-sections (Since a char has 8 bits = 1 byte)
).forEach(s -> // Go through each 8-char-section...
    sb.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char
);

String output = sb.toString(); // Output text (t)

and the compressed method printing to console:

Arrays.stream(input.split("(?<=\\G.{8})")).forEach(s -> System.out.print((char) Integer.parseInt(s, 2))); 
System.out.print('\n');

I am sure there are "better" ways to do this but this is the smallest one you can probably get.

like image 179
Leon Kasko Avatar answered Oct 25 '22 07:10

Leon Kasko


public static String binaryToText(String binary) {
    return Arrays.stream(binary.split("(?<=\\G.{8})"))/* regex to split the bits array by 8*/
                 .parallel()
                 .map(eightBits -> (char)Integer.parseInt(eightBits, 2))
                 .collect(
                                 StringBuilder::new,
                                 StringBuilder::append,
                                 StringBuilder::append
                 ).toString();
}
like image 39
Maroine Mlis Avatar answered Oct 25 '22 05:10

Maroine Mlis


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");
like image 45
tarka Avatar answered Oct 25 '22 05:10

tarka