为什么我不能从 char 类型转换为 int 类型?
由于某种原因,以下代码不起作用:
char cValue = '8';
int digits = (int)cValue;
它不断给出 5 或 7 的某个值,或者类似的值。
我只是好奇为什么 - 我使用的是 Character.getNumericValue(cValue);
。
为什么会发生这种情况?
For some reason, the following code does not work:
char cValue = '8';
int digits = (int)cValue;
It keeps giving some value of 5 or 7, or something along those lines.
I'm just curious why - I'm using Character.getNumericValue(cValue);
instead.
Why does this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将 char 类型转换为 int,事实上您就是这样。字符“8”的二进制表示实际上是 56(十进制)。有关转换,请参阅任何 ASCII 图表。您正在寻找的是解析,而不是转换。
getNumericValue()< /code>
解析该字符并给出其等价的数字。转换字符只是改变类型并保持位模式不变。然后根据与其关联的变量的类型来解释这些位。
You can typecast char to int, and in fact you are. The binary representation of the character '8' is actually 56 (decimal). See any ASCII chart for the conversions. What you're looking for is parsing, not casting.
getNumericValue()
parses the char and gives you its numeric equivalent. Casting the char simply changes the type and leaves the pattern of bits the same. The bits are then interpreted according to the type of the variable they're associated with.Java char 是一个无符号的 16 位值。当您将 1 转换为 int 时,您将获得该字符的 Unicode 值。字符“8”的 Unicode 值为十进制 56。
getNumericValue 完全不同 - 如果它是具有数字含义的字符,它会为您提供该字符的含义。
A Java char is an unsigned 16-bit value. When you cast one to int you get the Unicode value of the character. The character '8' has a Unicode value of decimal 56.
getNumericValue is entirely different -- it gives you the MEANING of the character, if it's a character with a numeric meaning.