Results 1 to 3 of 3
- 10-29-2011, 07:14 AM #1
Member
- Join Date
- Oct 2011
- Posts
- 15
- Rep Power
- 0
convert 30 char of ascii to binary
How to make a program that can accept 30 char of ascii than convert it into binary?
I already done this but this only can accept number not letter. Which part that i need to change?Java Code: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 = 1 << 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); } }
- 10-29-2011, 09:09 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,561
- Rep Power
- 11
Re: convert 30 char of ascii to binary
To be more precise your program accepts a string from the user and uses this to create an integer number which it converts.I already done this but this only can accept number not letter. Which part that i need to change?
There is no reason why you could not just read() rather than readLine(). This would give you an int directly without the need to parse anything, and the result string can be built up as you are already doing.
Of course this would convert only a single character - so you would need to put the whole process inside a loop so that it is done 30 times.
-----
You should follow Java coding style and (1) indent the code, and (2) Start the variable holding the current bit value with a lower case letter: bit.
"result+=0" had me confused for a moment. It would be far more readable if the string containing a zero digit were written as a string to make it clear you mean to concatenate rather than increment.
"while(true){...}" is more readable to my eye than "do{...}while(true)" - but that may be just me. I like to see the important loop bits "upfront" and, so, prefer while and if to do.Java Code:result += "0";
- 10-29-2011, 09:15 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,561
- Rep Power
- 11
Similar Threads
-
How to convert BCD to ascii
By slavicp in forum Advanced JavaReplies: 2Last Post: 04-05-2011, 11:54 AM -
How to convert BCD to ascii
By slavicp in forum New To JavaReplies: 2Last Post: 04-05-2011, 11:53 AM -
ASCII to binary code
By Vagabond.drv in forum New To JavaReplies: 12Last Post: 01-13-2011, 01:52 PM -
convert String to ASCII value
By uthpalaw in forum New To JavaReplies: 19Last Post: 09-17-2010, 03:02 PM -
Binary and ASCII
By mac in forum New To JavaReplies: 4Last Post: 01-10-2010, 06:31 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks