Convert char to int in C#
C#CharIntC# Problem Overview
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.
C# Solutions
Solution 1 - C#
This will convert it to an int
:
char foo = '2';
int bar = foo - '0';
This works because each character is internally represented by a number. The characters '0'
to '9'
are represented by consecutive numbers, so finding the difference between the characters '0'
and '2'
results in the number 2.
Solution 2 - C#
Interesting answers but the docs say differently:
> Use the GetNumericValue
methods to
> convert a Char
object that represents
> a number to a numeric value type. Use
> Parse
and TryParse
to convert a
> character in a string into a Char
> object. Use ToString
to convert a Char
> object to a String
object.
Solution 3 - C#
Has anyone considered using int.Parse()
and int.TryParse()
like this
int bar = int.Parse(foo.ToString());
Even better like this
int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
//Do something to correct the problem
}
It's a lot safer and less error prone
Solution 4 - C#
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');
}
Solution 5 - C#
Try This
char x = '9'; // '9' = ASCII 57
int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9
Solution 6 - C#
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.
Solution 7 - C#
This converts to an integer and handles unicode
CharUnicodeInfo.GetDecimalDigitValue('2')
You can read more here.
Solution 8 - C#
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;
}
Solution 9 - C#
The real way is:
> int theNameOfYourInt = (int).Char.GetNumericValue(theNameOfYourChar);
"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.
Solution 10 - C#
I am agree with @Chad Grant
Also right if you convert to string then you can use that value as numeric as said in the question
int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2
I tried to create a more simple and understandable example
char v = '1';
int vv = (int)char.GetNumericValue(v);
char.GetNumericValue(v) returns as double and converts to (int)
More Advenced usage as an array
int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();
Solution 11 - C#
First convert the character to a string and then convert to integer.
var character = '1';
var integerValue = int.Parse(character.ToString());
Solution 12 - 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
Solution 13 - C#
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
Solution 14 - C#
Use this:
public static string NormalizeNumbers(this string text)
{
if (string.IsNullOrWhiteSpace(text)) return text;
string normalized = text;
char[] allNumbers = text.Where(char.IsNumber).Distinct().ToArray();
foreach (char ch in allNumbers)
{
char equalNumber = char.Parse(char.GetNumericValue(ch).ToString("N0"));
normalized = normalized.Replace(ch, equalNumber);
}
return normalized;
}
Solution 15 - C#
One very quick simple way just to convert chars 0-9 to integers: C# treats a char value much like an integer.
char c = '7'; (ascii code 55) int x = c - 48; (result = integer of 7)
Solution 16 - C#
Use Uri.FromHex.
And to avoid exceptions Uri.IsHexDigit.
char testChar = 'e';
int result = Uri.IsHexDigit(testChar)
? Uri.FromHex(testChar)
: -1;
Solution 17 - C#
I was searched for the most optimized method and was very surprized that the best is the easiest (and the most popular answer):
public static int ToIntT(this char c) =>
c is >= '0' and <= '9'?
c-'0' : -1;
There a list of methods I tried:
c-'0' //current
switch //about 25% slower, no method with disabled isnum check (it is but performance is same as with enabled)
0b0000_1111 & (byte) c; //same speed
Uri.FromHex(c) /*2 times slower; about 20% slower if use my isnum check*/ (c is >= '0' and <= '9') /*instead of*/ Uri.IsHexDigit(testChar)
(int)char.GetNumericValue(c); // about 20% slower. I expected it will be much more slower.
Convert.ToInt32(new string(c, 1)) //3-4 times slower
Note that isnum check (2nd line in the first codeblock) takes ~30% of perfomance, so you should take it off if you sure that c
is char. The testing error was ~5%
Solution 18 - C#
This worked for me:
int bar = int.Parse("" + foo);
Solution 19 - C#
I've seen many answers but they seem confusing to me. Can't we just simply use Type Casting.
For ex:-
int s;
char i= '2';
s = (int) i;