Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Convert Text to Binary

 
 

Share on Google+Share on Google+

Convert Text to Binary

Advertisement
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:
Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 17, 2011

Related Tutorials

Discuss: Convert Text to Binary  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com