Question

I am trying to make a Java binary translator, and I have gotten to the part of translating the binary back to a String. I have made it to a byte array. I want to convert it to a string.

For example, I want a new byte array of {01000001, 01100001, 01000010, 01100010} to return "AaBb".

How can I do this?

Was it helpful?

Solution

I think what you really want to do is convert a binary (decimal) number to its ASCII representation. If so, try something like this:

public class ByteArrayToAsciiChar {

  public String byteToCharacter(byte b) {
    return Character.valueOf((char)b).toString();
  }

  public static void main(String[] args) {
    byte[] byteArray = {
        0b00100101,
        0b01000001,
        0b01100001,
        0b01000010,
        0b01100010,
        0b01010101
    };

    ByteArrayToAsciiChar testClass = new ByteArrayToAsciiChar();

    for (byte b : byteArray) {
      System.out.println("Byte: " + b + " ==> " + testClass.byteToCharacter(b));
    }

  }

}

Which gives this output:

Byte: 37 ==> %
Byte: 65 ==> A
Byte: 97 ==> a
Byte: 66 ==> B
Byte: 98 ==> b
Byte: 85 ==> U

HTH

OTHER TIPS

Erm ... it is as simple as this:

    byte[] bytes = {0b01000001, 0b01100001, 0b01000010, 0b01100010};
    String str = new String(bytes, "ASCII");

Of course, that assumes that the bytes represent ASCII encoded characters. If not then use the name of the actual character encoding.

If you are going to do this a lot, then it is worth looking up the Charset object for the character set and using the String(byte[], Charset) overload.

If you already have a byte array (exemplarily constructed below), you can easily pass the byte array to a new String (as Ingo suggested) and viola - you're done.

byte b[] = new byte[4];
b[0] = Byte.parseByte("01000001", 2);
b[1] = Byte.parseByte("01100001", 2);
b[2] = Byte.parseByte("01000010", 2);
b[3] = Byte.parseByte("01100010", 2);

String output = new String(b);

If you only have an array of binarys in form of strings, you could use this:

public String convertBinaryArrayToString(String binary[]) {
    String ret = null;
    for (String i : binary) {
        ret += (char) Byte.parseByte(i, 2);
    }
    return ret;
}

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top