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 o
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');
}
Comparison of some of the methods based on the result when the character is not an ASCII digit:
char c1 = (char)('0' - 1), c2 = (char)('9' + 1);
Debug.Print($"{c1 & 15}, {c2 & 15}"); // 15, 10
Debug.Print($"{c1 ^ '0'}, {c2 ^ '0'}"); // 31, 10
Debug.Print($"{c1 - '0'}, {c2 - '0'}"); // -1, 10
Debug.Print($"{(uint)c1 - '0'}, {(uint)c2 - '0'}"); // 4294967295, 10
Debug.Print($"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}"); // -1, -1
Interesting answers but the docs say differently:
Use the
GetNumericValue
methods to convert aChar
object that represents a number to a numeric value type. UseParse
andTryParse
to convert a character in a string into aChar
object. UseToString
to convert aChar
object to aString
object.
http://msdn.microsoft.com/en-us/library/system.char.aspx
This worked for me:
int bar = int.Parse("" + foo);
Principle:
char foo = '2';
int bar = foo & 15;
The binary of the ASCII charecters 0-9 is:
0 - 0011 0000
1 - 0011 0001
2 - 0011 0010
3 - 0011 0011
4 - 0011 0100
5 - 0011 0101
6 - 0011 0110
7 - 0011 0111
8 - 0011 1000
9 - 0011 1001
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:
public static int CharToInt(char c)
{
return 0b0000_1111 & (byte) c;
}
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)
char letterA = Convert.ToChar(65);
Console.WriteLine(letterA);
letterA = 'あ';
ushort valueA = Convert.ToUInt16(letterA);
Console.WriteLine(valueA);
char japaneseA = Convert.ToChar(valueA);
Console.WriteLine(japaneseA);
Works with ASCII char or Unicode char