在java中将int转换为char

在java中将int转换为char

本文介绍了在java中将int转换为char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是代码片段,

int a = 1;
char b = (char) a;
System.out.println(b);

但我得到的是空输出.

int a = '1';
char b = (char) a;
System.out.println(b);

我将得到 1 作为我的输出.

I will get 1 as my output.

有人能解释一下吗?如果我想像第一个片段那样将 int 转换为 char,我应该怎么做?

Can somebody explain this? And if I want to convert an int to a char as in the first snippet, what should I do?

推荐答案

int a = 1;
char b = (char) a;
System.out.println(b);

将打印出带有 Unicode 代码点 1(标题开头的字符,不可打印;请参阅此表:C0 控件和基本拉丁语, 同 ASCII)

will print out the char with Unicode code point 1 (start-of-heading char, which isn't printable; see this table: C0 Controls and Basic Latin, same as ASCII)

int a = '1';
char b = (char) a;
System.out.println(b);

将打印出 Unicode 码位为 49 的字符(对应于 '1')

will print out the char with Unicode code point 49 (one corresponding to '1')

如果你想转换一个数字 (0-9),你可以给它加上 48 并强制转换,或者类似 Character.forDigit(a, 10);.

If you want to convert a digit (0-9), you can add 48 to it and cast, or something like Character.forDigit(a, 10);.

如果要转换被视为 Unicode 代码点的 int,可以使用 Character.toChars(48) 例如.

If you want to convert an int seen as a Unicode code point, you can use Character.toChars(48) for example.

这篇关于在java中将int转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:41