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.
In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.
The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.
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.
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
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
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With