converting to ASCII
Author |
Message |
venomm
|
Posted: Wed Mar 31, 2010 6:19 pm Post subject: converting to ASCII |
|
|
Hello I want to make a program that takes a number entered by a user and converts it to its ascii form
I dont know I to convert to ASCII thats my only problem
heres my code
Quote:
import java.io.*;
class ASCII
{
public static void main (String args [])
throws java.io.IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String input = "";
int num = 0;
final int MAX = 126;
final int MIN = 33;
char convert = ' ';
System.out.println ("ASCII Converter");
System.out.println ("Please enter a number:");
input = br.readLine();
num = Integer.parseInt (input);
if (num > MAX)
{
System.out.println ("Number entered was too high.");
}
else if (num < MIN)
{
System.out.println ("Number entered was too low.");
System.out.println ("Please enter another number larger than "+MIN+".");
input = br.readLine();
num = Integer.parseInt (input);
}
else
{
convert.(char)=num
System.out.println ((int) num);
}
}
}
|
|
|
|
|
|
Sponsor Sponsor
|
|
|
DtY
|
Posted: Wed Mar 31, 2010 8:00 pm Post subject: RE:converting to ASCII |
|
|
You mean the user enters the ordinal value, and you output the character with that value?
You don't actually convert anything. ASCII doesn't exist, it's just a representation. A character is a single byte, and that tells the terminal (or whatever is displaying the output) where to look to for how to display that character.
(this may not work quite right, but I think it should)
What you want to do, is get the input from the user as an integer, then cast it to char ( (char)variable ), a `char` is just a one byte number, there's nothing (inherently) special about it, it's just shorter.
But, Java knows that if you tell it to output an int, you want to see that as a number (in base ten), but when you give it a char, you don't want to see it as a number, you want to see that character, so it's sent straight to the terminal (or otherwise) as a character, and not converted to a number.
The drawback (or maybe not, depending on what you want) is that this wont necessarily be ASCII, it will only be if you're on an OS that uses ASCII (or unicode, since it's backwards compatible), but if your OS uses a different character encoding, it will use the system encoding.
The good news is, no one uses anything else, so you don't need to worry about this unless you know that you have a system that doesn't use ASCII (or Unicode).
Linux, Mac OS X and Windows all use ASCII, so there's little to worry about. |
|
|
|
|
|
|
|