What is the proper way to convert a char
to int
?
This gives 49
:
int val = Convert.ToInt32('1');
//int val = Int32.Parse("1"); // Works
I don't want to convert to string and then parse it.
What is the proper way to convert a char
to int
?
This gives 49
:
int val = Convert.ToInt32('1');
//int val = Int32.Parse("1"); // Works
I don't want to convert to string and then parse it.
An extension of some other answers that covers hexadecimal representation:
how about (for
char c
)which does substraction of the char value?
Re the API question (comments), perhaps an extension method?
then use
int x = c.ParseInt32();
The binary of the ASCII charecters 0-9 is:
0 - 00110000
1 - 00110001
2 - 00110010
3 - 00110011
4 - 00110100
5 - 00110101
6 - 00110110
7 - 00110111
8 - 00111000
9 - 00111001
and if you take in each one of them the first 4 LSB(using bitwise AND with 8'b00001111 that equels to 15) you get the actual number (0000 = 0,0001=1,0010=2,... )
The most secure way to accomplish this is using Int32.TryParse method. See here: http://dotnetperls.com/int-tryparse
This can be done using ascii codes where '0' is the lowest and the number characters count up from there