Convert char to int in C#

2019-01-03 02:35发布

I have a char in c#:

char foo = '2';

Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work:

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

int.parse only works on strings as well.

Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.

标签: c# char int
13条回答
爷、活的狠高调
2楼-- · 2019-01-03 02:40

This will convert it to an int:

char foo = '2';
int bar = foo - '0';

This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.

查看更多
Bombasti
3楼-- · 2019-01-03 02:42

This worked for me:

int bar = int.Parse("" + foo);
查看更多
Root(大扎)
4楼-- · 2019-01-03 02:46

Try This

char x = '9'; // '9' = ASCII 57

int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9
查看更多
仙女界的扛把子
5楼-- · 2019-01-03 02:47
char c = '1';
int i = (int)(c-'0');

and you can create a static method out of it:

static int ToInt(this char c)
{
    return (int)(c - '0');
}
查看更多
迷人小祖宗
6楼-- · 2019-01-03 02:48

I've seen many answers but they seem confusing to me. Can't we just simply use Type Casting.

For ex:-

int s;
char i= '2';
s = (int) i;
查看更多
Lonely孤独者°
7楼-- · 2019-01-03 02:50

Interesting answers but the docs say differently:

Use the GetNumericValue methods to convert a Char object that represents a number to a numeric value type. Use Parse and TryParse to convert a character in a string into a Char object. Use ToString to convert a Char object to a String object.

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

查看更多
登录 后发表回答