How can I display the desired value in ASCII code inputted by me?
26,046
Solution 1
import java.io.*;
import java.lang.*;
public class CharToASCII{
public static void main(String args[]) throws IOException{
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the char:");
String str = buff.readLine();
for ( int i = 0; i < str.length(); ++i ){
char c = str.charAt(i);
int j = (int) c;// your work is done here
System.out.println("ASCII OF "+c +" = " + j + ".");
}
}
}
Solution 2
Just cast an integer value to char.:
int value = (int) 'a';
System.out.println((char) value); // prints a
If you need some literal output for ASCII values below '0', you'll need a mapping from the integer value (the ASCII number) to the literal, like this:
String[] literals0to32 = {"NUL", "SOH", "STX", /* to be continued */ };
private static String toLiteral(int value) {
if (value < 0 || value > 255)
throw new IKnowThatIHaveToValidateParametersException();
if (value < 32)
return literals0To32[value];
else
return (char) value;
}
Solution 3
You can print the corresponding Unicode Control Pictures, e.g. \u2400
for ␀ (nul
).
Comments
-
jhoanne over 1 year
I need Java code. Please help me. Example: when I enter the number in ASCII
0 the output will be nul 1 for soh 2 for stx until it reaches the max number of ASCII.
Consider this code. It outputs an ASCII number. How can I reverse it?
String test = "ABCD"; for ( int i = 0; i < test.length(); ++i ) { char c = test.charAt( i ); int j = (int) c; System.out.println(j); }
-
jhoanne over 13 yearsthanks, but how about when my prof. enter the number 0 it'll print nul.?
-
Andreas Dolk over 13 yearsNo, in that case it will print something undefined. Editing my answer for a quick solution (fragment) for ASCII
-
jmj over 13 years@jhoanne you need to make proper imports
-
jhoanne over 13 yearscan you reverse the output of this code? instead of enter the char: can you i use enter the ascii code. e.g. (Enter ascii code: 0 char of 0 is NUL
-
jmj over 13 years@jhoanne ya for that you need to convert
int
tochar
-
jhoanne over 13 yearscan you edit again by putting all the codes starts in public class. please.
-
jhoanne over 13 yearsinstead of enter the char: can you i use enter the ascii code. e.g. (Enter ascii code: 41, char of 41 is ) because i can convert int to char. pls help again
-
jmj over 13 years@jhoanne yes you can , I would suggest you to clear fundamentals , It would be trouble for you in future if you just follow this approch
-
Andreas Dolk over 13 years@jhoanne - of course ... not. ;) You've already accepted another answer and I already provided too much help for something that smells like homework. I'm not creating a copy'n'paste solution.
-
jhoanne over 13 yearssorry for that ;( thanks for giving me your info. it really helps me. but it is not my homework. sorry again.