Home Java Convert Text to Binary



Convert Text to Binary
Posted on: April 17, 2011 at 12:00 AM
In this section, we will learn how to convert Text to Binary. The following program provides you the functionality to convert Text to Binary

Convert Text to Binary

     

In this section, we will learn how to convert Text to Binary. The following program provides you the functionality to convert Text to Binary.

Code Description:

In the program code below, to take the input from the keyboard we have used BufferReader() method in which we have passed an object of it which is InputStreamReader() as must be knowing. Then we have defined a variable of type int which will convert the input to integer line by line. Now we have used a loop here to check the number we well input. It will take maximum of 24 bytes as we have declared maxBytes=3. Hence it will convert the number into bytes one by one. 

Here is the code of the program:

import java.io.*;

public class TexttoBinary {
  private static final int maxBytes = 3;
  public static void main(String[] args) {
  
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  do {
  try {
  System.out.print("Type the number to parse: ");
  int number = Integer.parseInt(in.readLine());
  int Bit;
  String result = "";
  for (int i = maxBytes*8; i >= 0; i--) {
  Bit = << i;
  if (number >= Bit) {
  result += 1;
  number -= Bit;
  }
  else {
  result += 0;
  }
  }
  System.out.println(result);
  }
  catch (NumberFormatException e) {
  System.exit(0);
  }
  catch (IOException e) {
  e.printStackTrace();
  System.exit(1);
  }
  }
  while (true);
  }
}

Output of the program:

C:\unique>javac TexttoBinary.java

C:\unique>java TexttoBinary
Type the number to parse: 417893
0000001100110000001100101
Type the number to parse: 3289
0000000000000110011011001
Type the number to parse:

Related Tags for Convert Text to Binary:


More Tutorials from this section

Ask Questions?    Discuss: Convert Text to Binary  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.