如何将ASCII码(0-255)转换为其对应的字符?
在 Java 中,如何将 ASCII 代码([0, 255] 范围内的整数)转换为其相应的 ASCII 字符?
例如:
65 -> "A"
102 -> "f"
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
Character.toString ( (字符) i);
Character.toString ((char) i);
System.out.println((char)65);
会打印“A”
System.out.println((char)65);
would print "A"
String.valueOf
<代码>(
Character.toChars(int)
< /a>)
假设整数如您所说,在 0 到 255 之间,您将从
Character.toChars
返回一个包含单个字符的数组,这将成为一个传递给String.valueOf
时为单字符字符串。使用
Character.toChars
优于涉及从int
到char
转换的方法(即(char) i
)出于多种原因,包括如果您未能正确验证整数,则Character.toChars
将抛出IllegalArgumentException
,而强制转换将吞掉错误(根据 缩小原始转换规范),可能会给出与您不同的输出故意的。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 toString.valueOf
.Using
Character.toChars
is preferable to methods involving a cast fromint
tochar
(i.e.(char) i
) for a number of reasons, including thatCharacter.toChars
will throw anIllegalArgumentException
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.这是一个简单的解决方案
it is a simple solution
您最终将得到一个长度为 1 的字符串,其单个字符的 (ASCII) 代码为 65。在 Java 中,字符是数字数据类型。
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.
执行相同操作的更简单方法:
键入将整数转换为字符,让
int n
为整数,然后:
An easier way of doing the same:
Type cast integer to character, let
int n
be the integer,then:
可以像这样从 a 迭代到 z
One can iterate from a to z like this
这是一个例子,说明通过将int转换为char,可以确定ASCII码对应的字符。
This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.
上面的答案仅接近解决问题。这是你的答案:
Integer.decode(Character.toString(char c));
upper answer only near solving the Problem. heres your answer:
Integer.decode(Character.toString(char c));