What's the “java” way of converting chars (dig

2020-02-23 06:00发布

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
....

6条回答
我只想做你的唯一
2楼-- · 2020-02-23 06:11

Convert to Ascii then subtract 48.

(int) '7' would be 55 
((int) '7') - 48 = 7 
((int) '9') - 48 = 9 
查看更多
混吃等死
3楼-- · 2020-02-23 06:15

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');
查看更多
4楼-- · 2020-02-23 06:19

I'd strongly prefer Character.digit.

查看更多
够拽才男人
6楼-- · 2020-02-23 06:37

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.

查看更多
SAY GOODBYE
7楼-- · 2020-02-23 06:37

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;
查看更多
登录 后发表回答