如何将 ASCII 码(0-255)转换为相应的字符?

如何在 Java 中将 ASCII 代码(从[0,255]范围的整数)转换为对应的 ASCII 字符?

例如:

65  -> "A"
102 -> "f"
695458 次浏览

String.valueOf (Character.toChars(int))

如您所说,假设整数在0到255之间,您将从 Character.toChars返回一个带有单个字符的数组,当传递给 String.valueOf时,该数组将成为一个单个字符的字符串。

使用 Character.toChars优于从 intchar(即 (char) i)进行转换的方法,原因有很多,包括如果不能正确验证整数,Character.toChars将抛出 IllegalArgumentException,而转换将吞噬错误(每个 窄化基元转换规范) ,可能给出与预期不同的输出。

    new String(new char[] { 65 })

您将得到一个长度为1的字符串,其单个字符的(ASCII)代码为65。在 Java 字符中是数字数据类型。

System.out.println((char)65); 会打印出“ A”

可以像这样从 a 到 z 进行迭代

int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}

做同样事情的一个更简单的方法是:

输入整数转换为字符,让 int n为整数, 然后:

Char c=(char)n;
System.out.print(c)//char c will store the converted value.
int number = 65;
char c = (char)number;

这是一个简单的解决方案

这是一个示例,表明通过将 int 转换为 char,可以确定对应的字符为 ASCII 代码。

public class sample6
{
public static void main(String... asf)
{


for(int i =0; i<256; i++)
{
System.out.println( i + ". " + (char)i);
}
}
}

上面的答案只接近解决问题。这是你的答案:

Decode (Charter.toString (char c)) ;

    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);