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?
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.
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) .
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.
instead of
String out = new Character((char)k).toString();
do
String out = String.valueOf(k);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With