How to convert ASCII code (0-255) to its corresponding character?
How can I convert, in Java, the ASCII code (which is an integer from [0, 255] range) to its corresponding ASCII character?
For example:
65开发者_运维技巧 -> "A"
102 -> "f"
Character.toString ((char) i);
System.out.println((char)65);
would print "A"
String.valueOf
(
Character.toChars(int)
)
Assuming the integer is, as you say, between 0 and 255, you'll get an array with a single character back from Character.toChars
, which will become a single-character string when passed to String.valueOf
.
Using Character.toChars
is preferable to methods involving a cast from int
to char
(i.e. (char) i
) for a number of reasons, including that Character.toChars
will throw an IllegalArgumentException
if you fail to properly validate the integer while the cast will swallow the error (per the narrowing primitive conversions specification), potentially giving an output other than what you intended.
int number = 65;
char c = (char)number;
it is a simple solution
new String(new char[] { 65 })
You will end up with a string of length one, whose single character has the (ASCII) code 65. In Java chars are numeric data types.
An easier way of doing the same:
Type cast integer to character, let int n
be the integer,
then:
Char c=(char)n;
System.out.print(c)//char c will store the converted value.
One can iterate from a to z like this
int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}
for (int i = 0; i < 256; i++) {
System.out.println(i + " -> " + (char) i);
}
char lowercase = 'f';
int offset = (int) 'a' - (int) 'A';
char uppercase = (char) ((int) lowercase - offset);
System.out.println("The uppercase letter is " + uppercase);
String numberString = JOptionPane.showInputDialog(null,
"Enter an ASCII code:",
"ASCII conversion", JOptionPane.QUESTION_MESSAGE);
int code = (int) numberString.charAt(0);
System.out.println("The character for ASCII code "
+ code + " is " + (char) code);
This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.
public class sample6
{
public static void main(String... asf)
{
for(int i =0; i<256; i++)
{
System.out.println( i + ". " + (char)i);
}
}
}
upper answer only near solving the Problem. heres your answer:
Integer.decode(Character.toString(char c));
精彩评论