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

Explanation

In Java every char can be seen as a numeric value between 0 and 65535. The numeric value of a char is it’s ASCII value (or, to be precise, it’s code point). Since '0', … '9' follow sequentially in ASCII, we have

  • '0' - '0' = 0
  • '1' - '0' = 1
  • '2' - '0' = 2
  • '9' - '0' = 9

In other words 'n' - '0' = n for 0 ≤ n ≤ 9.

Comments (1)

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

by georgeek | 
Reply

Add comment