Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: converting binary to text?

Tags:

java

binary

I wrote this code for converting binary to text .

public static void main(String args[]) throws IOException{

      BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter a binary value:");
      String h = b.readLine();
      int k = Integer.parseInt(h,2);  
      String out = new Character((char)k).toString();
      System.out.println("string: " + out);
      } 
}

and look at the output !

Enter a binary value:
0011000100110000
string: ?

what's the problem?

like image 368
Aida E Avatar asked Apr 23 '12 15:04

Aida E


People also ask

Is there a binary data type 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.

How do you convert a string to binary?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

How do you convert int to binary in Java?

To convert an integer to binary, we can simply call the public static String toBinaryString(int i) method of the Integer class. This method returns the binary string that corresponds to the integer passed as an argument to this function.


1 Answers

instead of

String out = new Character((char)k).toString();

do

String out = String.valueOf(k);

EDIT:

String input = "011000010110000101100001";
String output = "";
for(int i = 0; i <= input.length() - 8; i+=8)
{
    int k = Integer.parseInt(input.substring(i, i+8), 2);
    output += (char) k;
}   
like image 164
juergen d Avatar answered Sep 27 '22 21:09

juergen d