Java: Converting a char to an int
Digits: Converting character '5' to integer 5:
char c = '5';
int i = c - '0'; // i == 5
ASCII: Converting 'A' to 65:
char c = 'A';
int i = c; // i == 65
Ehm, what?!
In Java a char has a dual interpretation in the form of it's numerical ASCII value (or code point to be precise). We here use the fact that '0', … '9' have sequential ASCII values ('0' has value 48, '1' has value 49, and so on). This means that 'n' - '0' = n.
'0' - '0'= 48 - 48 = 0'1' - '0'= 49 - 48 = 1'2' - '0'= 50 - 48 = 2- …
'9' - '0'= 57 - 48 = 9
Comments (3)
What happens if you add a number, say 5 to C or any other character?
by Anonymous |
If you add 5 to C you'll get an H (or 72 if you look at it as an int). You can try running this yourself: System.out.println('C' + 5);.
Also a standard
Character.digitmethod could be used. E.g.Character.digit('9', 10) == 9(int).by georgeek |