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:50

By default you use UNICODE so I suggest using faulty's method

int bar = int.Parse(foo.ToString());

Even though the numeric values under are the same for digits and basic Latin chars.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-03 02:52

This converts to an integer and handles unicode

CharUnicodeInfo.GetDecimalDigitValue('2')

You can read more here.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-03 02:53

Comparison of some of the methods based on the result when the character is not an ASCII digit:

char c = '\n';                              
Debug.Print($"{c & 15}");                   // 10
Debug.Print($"{c ^ 48}");                   // 58
Debug.Print($"{c - 48}");                   // -38
Debug.Print($"{(uint)c - 48}");             // 4294967258
Debug.Print($"{char.GetNumericValue(c)}");  // -1 
查看更多
狗以群分
5楼-- · 2019-01-03 02:54

The real way is:

int theNameOfYourInt = (int).Char.GetNumericValue(theNameOfYourChar);

"theNameOfYourInt" - the int you want your char to be transformed to.

"theNameOfYourChar" - The Char you want to be used so it will be transformed into an int.

Leave everything else be.

查看更多
你好瞎i
6楼-- · 2019-01-03 02:54

Principle:

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

The binary of the ASCII charecters 0-9 is:

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

and if you take in each one of them the first 4 LSB (using bitwise AND with 8'b00001111 that equals to 15) you get the actual number (0000 = 0,0001=1,0010=2,... )

Usage:

public static int CharToInt(char c)
{
    return 0b0000_1111 & (byte) c;
}
查看更多
爷的心禁止访问
7楼-- · 2019-01-03 03:00

I'm using Compact Framework 3.5, and not has a "char.Parse" method. I think is not bad to use the Convert class. (See CLR via C#, Jeffrey Richter)

char letterA = Convert.ToChar(65);
Console.WriteLine(letterA);
letterA = 'あ';
ushort valueA = Convert.ToUInt16(letterA);
Console.WriteLine(valueA);
char japaneseA = Convert.ToChar(valueA);
Console.WriteLine(japaneseA);

Works with ASCII char or Unicode char

查看更多
登录 后发表回答