Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert char to int?

Tags:

c#

.net

People also ask

How do I convert a char to an int in c?

We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.

How do I convert a char to an int in R?

Convert a Character Object to Integer in R Programming – as. integer() Function. as. integer() function in R Language is used to convert a character object to integer object.

How do you convert char to int in Python?

To convert Python char to int, use the ord() method. The ord() is a built-in Python function that accepts a character and returns the ASCII value of that character. The ord() method returns the number representing the Unicode code of a specified character.


I'm surprised nobody has mentioned the static method built right into System.Char...

int val = (int)Char.GetNumericValue('8');
// val == 8

how about (for char c)

int i = (int)(c - '0');

which does substraction of the char value?

Re the API question (comments), perhaps an extension method?

public static class CharExtensions {
    public static int ParseInt32(this char value) {
        int i = (int)(value - '0');
        if (i < 0 || i > 9) throw new ArgumentOutOfRangeException("value");
        return i;
    }
}

then use int x = c.ParseInt32();


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

int val = '1' - '0';

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.


int i = (int)char.GetNumericValue(c);

Yet another option:

int i = c & 0x0f;

This should accomplish this as well.


int val = '1' - '0';

This can be done using ascii codes where '0' is the lowest and the number characters count up from there