29

Given the following code:

    char x = '5';
    int a0 = x - '0'; // 0
    int a1 = Integer.parseInt(x + ""); // 1
    int a2 = Integer.parseInt(Character.toString(x)); // 2
    int a3 = Character.digit(x, 10); // 3
    int a4 = Character.getNumericValue(x); // 4
    System.out.printf("%d %d %d %d %d", a0, a1, a2, a3, a4);

(version 4 credited to: casablanca)

What do you consider to be the "best-way" to convert a char into an int ? ("best-way" ~= idiomatic way)

We are not converting the actual numerical value of the char, but the value of the representation.

Eg.:

convert('1') -> 1
convert('2') -> 2
....
Community
  • 1
  • 1
Andrei Ciobanu
  • 12,500
  • 24
  • 85
  • 118
  • 3
    I'm pretty sure anybody coming from those ancient C and Pascal things, like me, would vote for first option. – Nikita Rybak Oct 16 '10 at 17:59
  • 1
    @Nikita: I do come from those "ancient C and Pascal things", but unless performance is absolutely critical, I would prefer a more expressive way than `x - '0'`. – casablanca Oct 16 '10 at 18:11
  • 1
    Does this answer your question? [Java: parse int value from a char](https://stackoverflow.com/questions/4968323/java-parse-int-value-from-a-char) – user202729 Jan 27 '21 at 12:53

6 Answers6

47

How about Character.getNumericValue?

casablanca
  • 69,683
  • 7
  • 133
  • 150
16

I'd strongly prefer Character.digit.

jacobm
  • 13,790
  • 1
  • 25
  • 27
8

The first method. It's the most lightweight and direct, and maps to what you might do in other (lower-level) languages. Of course, its error handling leaves something to be desired.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
4

If speed is critical (rather than validation you can combine the result) e.g.

char d0 = '0';
char d1 = '4';
char d2 = '2';
int value = d0 * 100 + d1 * 10 + d2 - '0' * 111;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
-1

Convert to Ascii then subtract 48.

(int) '7' would be 55 
((int) '7') - 48 = 7 
((int) '9') - 48 = 9 
ben
  • 9
-2

The best way to convert a character of a valid digit to an int value is below. If c is larger than 9 then c was not a digit. Nothing that I know of is faster than this. Any digits in ASCII code 0-9(48-57) ^ to '0'(48) will always yield 0-9. From 0 to 65535 only 48 to 57 yield 0 to 9 in their respective order.

int charValue = (charC ^ '0');
Kevin Ng
  • 2,146
  • 1
  • 13
  • 18