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.
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.
I'm surprised nobody has mentioned the static method built right into
System.Char
...You can try something like this:
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
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.Yet another option:
This should accomplish this as well.
You may use the following extension method: