char to int conversion

十年热恋 提交于 2020-01-05 08:52:38

问题


So I have something like this:

char cr = "9783815820865".charAt(0);
System.out.println(cr);   //prints out 9

If I do this:

 int cr = "9783815820865".charAt(0);
 System.out.println(cr);   //prints out 57

I understand that the conversion between char and int is not simply from '9' to 9. My problem is right now I simply need to keep the 9 as the int value, not 57. How to get the value 9 instead of 57 as a int type?


回答1:


You can try with:

int cr = "9783815820865".charAt(0) - '0';

charAt(0) will return '9' (as a char), which is a numeric type. From this value we'll just subtract the value of '0', which is again numeric and is exactly nine entries behind the entry of the '9' character in the ASCII table.

So, behind the scenes, the the subtraction will work with the ASCII codes of '9' and '0', which means that 57 - 48 will be calculated.




回答2:


try this:

char c = "9783815820865".charAt(0);
int cr = Integer.parseInt(c+"");



回答3:


Using Character#getNumericValue may be more idiomatic. Bear in mind that it'll convert anything above 'A' as 10.

int cr = Character.getNumericValue("9783815820865".charAt(0));
System.out.println(cr);


来源:https://stackoverflow.com/questions/32051600/char-to-int-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!