简体   繁体   中英

char to int conversion

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?

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.

try this:

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM