How to convert char to int?

2020-01-23 05:04发布

What is the proper way to convert a char to int? This gives 49:

int val = Convert.ToInt32('1');
//int val = Int32.Parse("1"); // Works

I don't want to convert to string and then parse it.

标签: c# .net
11条回答
欢心
2楼-- · 2020-01-23 05:23

I'm surprised nobody has mentioned the static method built right into System.Char...

int val = (int)Char.GetNumericValue('8');
// val == 8
查看更多
走好不送
3楼-- · 2020-01-23 05:28

You can try something like this:

int val = Convert.ToInt32("" + '1');
查看更多
叼着烟拽天下
4楼-- · 2020-01-23 05:30

What everyone is forgeting is explaining WHY this happens.

A Char, is basically an integer, but with a pointer in the ASCII table. All characters have a corresponding integer value as you can clearly see when trying to parse it.

Pranay has clearly a different character set, thats why HIS code doesnt work. the only way is

int val = '1' - '0';

because this looks up the integer value in the table of '0' which is then the 'base value' subtracting your number in char format from this will give you the original number.

查看更多
Deceive 欺骗
5楼-- · 2020-01-23 05:35
int i = (int)char.GetNumericValue(c);

Yet another option:

int i = c & 0x0f;

This should accomplish this as well.

查看更多
走好不送
6楼-- · 2020-01-23 05:39

You may use the following extension method:

public static class CharExtensions
    {
        public static int CharToInt(this char c)
        {
            if (c < '0' || c > '9')
                throw new ArgumentException("The character should be a number", "c");

            return c - '0';
        }
    }
查看更多
登录 后发表回答