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.
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.
This converts to an integer and handles unicode
CharUnicodeInfo.GetDecimalDigitValue('2')
You can read more here.
Comparison of some of the methods based on the result when the character is not an ASCII digit:
The real way is:
"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.
Principle:
The binary of the ASCII charecters 0-9 is:
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:
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)
Works with ASCII char or Unicode char