我在c#中有一个char:

char foo = '2';

现在我想把2变成一个整型。我发现皈依。ToInt32返回该字符的实际十进制值,而不是数字2。以下是可行的方法:

int bar = Convert.ToInt32(new string(foo, 1));

int。解析也只适用于字符串。

c#中没有本地函数可以在不使其成为字符串的情况下从char转换为int吗?我知道这是微不足道的,但这似乎很奇怪,没有本地直接进行转换。


当前回答

这将转换为整数并处理unicode

CharUnicodeInfo.GetDecimalDigitValue('2')

你可以在这里阅读更多。

其他回答

我搜索了最优化的方法,并非常惊讶地发现,最好的方法是最简单的(也是最流行的答案):

public static int ToIntT(this char c) =>
    c is >= '0' and <= '9'?
        c-'0' : -1;

下面是我尝试过的一些方法:

c-'0' //current
switch //about 25% slower, no method with disabled isnum check (it is but performance is same as with enabled)
0b0000_1111 & (byte) c; //same speed
Uri.FromHex(c) /*2 times slower; about 20% slower if use my isnum check*/ (c is >= '0' and <= '9') /*instead of*/ Uri.IsHexDigit(testChar)
(int)char.GetNumericValue(c); // about 20% slower. I expected it will be much more slower.
Convert.ToInt32(new string(c, 1)) //3-4 times slower

请注意,isnum检查(第一个代码块中的第二行)占用了大约30%的性能,所以如果您确定c是char,则应该取消它。测试误差为~5%

我更喜欢切换方法。 性能与c - '0'相同,但我发现开关更容易阅读。

基准:

Method Mean Error StdDev Allocated Memory/Op
CharMinus0 90.24 us 7.1120 us 0.3898 us 39.18 KB
CharSwitch 90.54 us 0.9319 us 0.0511 us 39.18 KB

代码:

public static int CharSwitch(this char c, int defaultvalue = 0) {
    switch (c) {
        case '0': return 0;
        case '1': return 1;
        case '2': return 2;
        case '3': return 3;
        case '4': return 4;
        case '5': return 5;
        case '6': return 6;
        case '7': return 7;
        case '8': return 8;
        case '9': return 9;
        default: return defaultvalue;
    }
}
public static int CharMinus0(this char c, int defaultvalue = 0) {
    return c >= '0' && c <= '9' ? c - '0' : defaultvalue;
}

有趣的答案,但医生说的不一样:

使用GetNumericValue方法 转换表示的Char对象 数值类型的数字。使用 和TryParse来转换 字符串中的字符转换为Char类型 对象。使用ToString转换Char类型 object转换为String对象。

http://msdn.microsoft.com/en-us/library/system.char.aspx

我见过很多答案,但我觉得很困惑。我们不能简单地使用类型转换吗?

例:-

int s;
char i= '2';
s = (int) i;

原则:

char foo = '2';
int bar = foo & 15;

ASCII字符0-9的二进制为:

0   -   0011 0000
1   -   0011 0001
2   -   0011 0010
3   -   0011 0011
4   -   0011 0100
5   -   0011 0101
6   -   0011 0110
7   -   0011 0111
8   -   0011 1000
9   -   0011 1001

如果你把前4个LSB(使用位and和8'b00001111,等于15),你会得到实际的数字(0000 = 0,0001=1,0010=2,…)

用法:

public static int CharToInt(char c)
{
    return 0b0000_1111 & (byte) c;
}