Char to integer conversion in C #

4

Reading a blog article, I came across the following syntax for converting char to integer:

string value = "123";
foreach (var c in value)
{
    if (char.IsDigit(c))
    {
        int digito = c - '0';
    }
}

I wonder why this conversion works.

    
asked by anonymous 24.05.2018 / 15:52

3 answers

4

All char is a corresponding integer of the ASCII table, and '0' is the base value of that table, ie all characters have a corresponding integer value and in a subtraction operation the result is the corresponding integer of that table, so it works.

24.05.2018 / 16:17
3

According to the documentation from C #, char can be implicitly converted to int

  

(...) char can be implicitly converted to ushort , int , uint , long , ulong , float , double or 'decimal. >

However, beware of unexpected results. The explanation of @VirgilioNovic justifies why operations like this:

char op1 = '3';
char op2 = '1';

Console.WriteLine("Resultado: " + (op1 + op2).ToString());

Does not result in 4:

'Resultado: 100'

Because (int)op1 is 51 and (int)op2 is 49 .

See this example in dotnetfiddle. ;

    
24.05.2018 / 16:36
0

You should use ToString () to not use the ASC code and then TryParse to check if it is integer.

string value = "123";
foreach (var c in value)
        {
            short digito;
            if(Int16.TryParse(c.ToString(),out digito))
            {
                Console.WriteLine(digito);
            }                
        }
        Console.ReadKey();
    
25.05.2018 / 04:36