0

I have a binary code (say "0100001001000011") and I am going to convert the value to the corresponding characters.

  1. scan the binary code from left to right, eight bits per unit. (Then you can get two binary string, 01000010 and 01000011)

Can anyone help me to code no.1 in Java?

cedbeu
  • 1,919
  • 14
  • 24
HSC
  • 129
  • 6
  • 3
    Possible duplicate of [Binary to text in Java](http://stackoverflow.com/questions/4211705/binary-to-text-in-java) – Kyle Mar 09 '16 at 03:11
  • You need to know the character set and encoding. ASCII could be it but so could IBM437, Windows-1252, UTF-8, and on and on—there are dozens. – Tom Blodget Mar 10 '16 at 06:18

2 Answers2

0

Sure...

String str = Arrays.stream(binary.split("(?<=\\G.{8})"))
  .map(s -> Integer.parseInt(s, 2)).map(i -> ""+(char)i)
  .collect(Collectors.joining(""));

Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

This method will convert a string containing binary code to an ASCII string represented by the String parameter.

public static String binaryToString(String binary){
    String output = "";
    for (int i=0; i<binary.length(); i+=8){
        String next = binary.substring(i,i+8);
        int code = Integer.parseInt(next,2);
        output += ((char) code);
    }
    return output;
}

Basically use Integer.parseInt(String s, int radix) to convert a String to a number with the given base (or radix), then typecast that to a char.

Jonah Haney
  • 521
  • 3
  • 12