Convert char to int in C#

Viewed 527276

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.

19 Answers

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.

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

Has anyone considered using int.Parse() and int.TryParse() like this

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

Even better like this

int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
    //Do something to correct the problem
}

It's a lot safer and less error prone

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');
}

I am agree with @Chad Grant

Also right if you convert to string then you can use that value as numeric as said in the question

int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2

I tried to create a more simple and understandable example

char v = '1';
int vv = (int)char.GetNumericValue(v); 

char.GetNumericValue(v) returns as double and converts to (int)

More Advenced usage as an array

int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();

First convert the character to a string and then convert to integer.

var character = '1';
var integerValue = int.Parse(character.ToString());

Use this:

public static string NormalizeNumbers(this string text)
{
    if (string.IsNullOrWhiteSpace(text)) return text;

    string normalized = text;

    char[] allNumbers = text.Where(char.IsNumber).Distinct().ToArray();

    foreach (char ch in allNumbers)
    {
        char equalNumber = char.Parse(char.GetNumericValue(ch).ToString("N0"));
        normalized = normalized.Replace(ch, equalNumber);
    }

    return normalized;
}

One very quick simple way just to convert chars 0-9 to integers: C# treats a char value much like an integer.

char c = '7'; (ascii code 55) int x = c - 48; (result = integer of 7)

Use Uri.FromHex.
And to avoid exceptions Uri.IsHexDigit.

char testChar = 'e';
int result = Uri.IsHexDigit(testChar) 
               ? Uri.FromHex(testChar)
               : -1;

I was searched for the most optimized method and was very surprized that the best is the easiest (and the most popular answer):

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

There a list of methods I tried:

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

Note that isnum check (2nd line in the first codeblock) takes ~30% of perfomance, so you should take it off if you sure that c is char. The testing error was ~5%

Related