[c#] Convert char to int in C#

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.

This question is related to c# char int

The answer is


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.


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


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


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.


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();

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.


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


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;

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.


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;
}

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');
}

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 worked for me:

int bar = int.Parse("" + foo);

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();

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');
}

Try This

char x = '9'; // '9' = ASCII 57

int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9

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


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

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

This converts to an integer and handles unicode

CharUnicodeInfo.GetDecimalDigitValue('2')

You can read more here.


This worked for me:

int bar = int.Parse("" + foo);

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.


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


Try This

char x = '9'; // '9' = ASCII 57

int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9

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;

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.


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to char

How can I convert a char to int in Java? C# - How to convert string to char? How to take character input in java Char Comparison in C Convert Char to String in C cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' How to get the real and total length of char * (char array)? Why is conversion from string constant to 'char*' valid in C but invalid in C++ char *array and char array[] C++ - How to append a char to char*?

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift