130

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.

0

11 Answers 11

297

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

int val = (int)Char.GetNumericValue('8');
// val == 8
6
  • 19
    Good spot! +1 Very odd that it returns a double, though Sep 8, 2010 at 9:16
  • 4
    I agree, I can't figure out why it returns 'double' - how can a single character possibly represent a floating-point number? Sep 8, 2010 at 16:25
  • 51
    There are many Unicode characters that do represent a non-integer number, e.g., U+2153.
    – dtb
    Sep 13, 2010 at 12:24
  • 26
    @dtb - I hadn't considered that. Char.GetNumericValue('⅓') does indeed return 0.3333.... Thanks for pointing that out! Sep 15, 2010 at 17:15
  • 1
    Foot Note: this function is currently not available in NetMF.
    – GisMofx
    Aug 10, 2015 at 12:32
39

how about (for char c)

int i = (int)(c - '0');

which does substraction of the char value?

Re the API question (comments), perhaps an extension method?

public static class CharExtensions {
    public static int ParseInt32(this char value) {
        int i = (int)(value - '0');
        if (i < 0 || i > 9) throw new ArgumentOutOfRangeException("value");
        return i;
    }
}

then use int x = c.ParseInt32();

7
  • 1
    I should have mentioned, I knew about this but is there any other way? I wanted to know if there is an API to do this?
    – tvr
    Sep 8, 2010 at 8:22
  • 4
    If you want a bahavior similiar to int.Parse, i.e. that an exception is thrown on invalid input you would need to add additional bounds checking: if (i < 0 || i > 9) throw new FormatException(); Sep 8, 2010 at 8:23
  • @user386338 I'm afraid that there is not. Sep 8, 2010 at 8:25
  • @user386338 - updated with an option re API, also including @0xA3's feedback Sep 8, 2010 at 9:13
  • @user386338 - see Joel's answer for an inbuilt API method Sep 8, 2010 at 9:15
21

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.

16
int i = (int)char.GetNumericValue(c);

Yet another option:

int i = c & 0x0f;

This should accomplish this as well.

4
int val = '1' - '0';

This can be done using ascii codes where '0' is the lowest and the number characters count up from there

1
  • This is brilliant! imo the most elegant solution here.
    – arabisoft
    Mar 23, 2020 at 10:17
3
int val = '1' - 48;
1
  • @Luke Xu : '0' has ASCII code 0x30 which is 48 in decimal so this is the same as '1' - '0'
    – NiKiZe
    Mar 9, 2018 at 13:49
3

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';
        }
    }
3
  • 1
    @0xA3 The range check has to be at the beginning of the method in general. Semantically if we are to convert char to int we have to check range of the input parameter, not the output int value. Sep 8, 2010 at 11:04
  • There is no need to check result int value because the range of numeric chars was performed at the start of the method, so there will be correct resulting value, if specified char is not in the range of numeric chars there will be thrown exception. The same logic as you provided but range check is performed at the beginning of the method. Sep 8, 2010 at 12:09
  • Sorry, I was misreading your code sample. Sometimes it's hard to see the most obvious things. I'd bet that the code said if (c < 0 || c > 9)... Sep 8, 2010 at 13:03
1

The most secure way to accomplish this is using Int32.TryParse method. See here: http://dotnetperls.com/int-tryparse

4
  • TryParse is for strings not for chars
    – tvr
    Sep 8, 2010 at 8:40
  • Yes it is but stille the most secure way to accomplish the conversion
    – MUG4N
    Sep 8, 2010 at 8:42
  • 1
    Converting a single character to an integer is a security matter? Sep 8, 2010 at 9:06
  • 1
    'Secure' in this case means that it won't cause problems if your char isn't actually an ascii number - it could be a multi-byte unicode character. May 1, 2012 at 10:54
1
int val = '1' & 15;

The binary of the ASCII charecters 0-9 is:

0   -   00110000

1   -   00110001

2   -   00110010

3   -   00110011

4   -   00110100

5   -   00110101

6   -   00110110

7   -   00110111

8   -   00111000

9   -   00111001

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

2
  • How does this work in terms of types? you are using a bitwise operator between a char and an int and then returns an int? Does the logical AND uses the binary representation of both the char and the int and return a binary representation and then as you are defining the var as an int it uses that representation?
    – mitomed
    Jun 7, 2018 at 21:59
  • @mitnomed yes and if you use byte for example then it uses the byte representation. Jun 10, 2018 at 8:00
0

You can try something like this:

int val = Convert.ToInt32("" + '1');
3
  • why not just .ToString()?
    – Veikedo
    Feb 25, 2016 at 9:18
  • @Veikedo he wants an int, and not a string.
    – briba
    Apr 28, 2016 at 14:15
  • 6
    I mean Convert.ToInt32('1'.ToString())
    – Veikedo
    Apr 28, 2016 at 17:15
0

An extension of some other answers that covers hexadecimal representation:

public int CharToInt(char c) 
{
    if (c >= '0' && c <= '9') 
    {
        return c - '0';
    }
    else if (c >= 'a' && c <= 'f') 
    {
        return 10 + c - 'a';
    }
    else if (c >= 'A' && c <= 'F') 
    {
        return 10 + c - 'A';
    }

    return -1;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.