Java中将字符转换为整数 [英] Converting characters to integers in Java

查看:30
本文介绍了Java中将字符转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释一下这里发生了什么:

Can someone please explain to me what is going on here:

char c = '+';
int i = (int)c;
System.out.println("i: " + i + " ch: " + Character.getNumericValue(c));

这会打印 i: 43 ch:-1.这是否意味着我必须依靠原始转换将 char 转换为 int?那么如何将 Character 转换为 Integer?

This prints i: 43 ch:-1. Does that mean I have to rely on primitive conversions to convert char to int? So how can I convert a Character to Integer?

是的,我知道 Character.getNumericValue 返回 -1 如果它不是数值并且对我有意义.问题是:为什么进行原始转换会返回 43?

Yes I know Character.getNumericValue returns -1 if it is not a numeric value and that makes sense to me. The question is: why does doing primitive conversions return 43?

Edit2: 43+ 的 ASCII,但我希望转换不会像 getNumericValue没有成功.否则这意味着有两种语义等价的方式来执行相同的操作但结果不同吗?

43 is the ASCII for +, but I would expect the cast to not succeed just like getNumericValue did not succeed. Otherwise that means there are two semantic equivalent ways to perform the same operation but with different results?

推荐答案

Character.getNumericValue(c)

java.lang.Character.getNumericValue(char ch) 返回指定 Unicode 字符表示的 int 值.例如,字符 'u216C'(罗马数字 50)将返回一个值为 50 的 int.

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character 'u216C' (the roman numeral fifty) will return an int with a value of 50.

字母 AZ 大写 ('u0041' 到 'u005A')、小写 ('u0061' 到 'u007A') 和完整宽度变体 ('uFF21' 到 'uFF3A' 和 'uFF41' 到 'uFF5A') 形式具有从 10 到 35 的数值.这独立于 Unicode 规范,它不为这些字符值分配数值.

The letters A-Z in their uppercase ('u0041' through 'u005A'), lowercase ('u0061' through 'u007A'), and full width variant ('uFF21' through 'uFF3A' and 'uFF41' through 'uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

该方法返回字符的数值,作为非负整数值;

This method returns the numeric value of the character, as a nonnegative int value;

-2 如果字符的数值不是非负整数;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 如果字符没有数值.

-1 if the character has no numeric value.

这里是链接.

这篇关于Java中将字符转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆