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.

Comments (1)

User avatar

Also a standard Character.digit method could be used. E.g. Character.digit('9', 10) == 9 (int).

by georgeek |  Reply

Add comment