Why does Convert.ToInt32('1') returns 49? [duplicate]
Possible Duplicate:
c# convert char to int
This works:
int val = Convert.ToInt32("1");
But this doesn't:
int val = Convert.ToInt32('1'); // returns 49
Shouldn't this con开发者_如何学Pythonvert to actual int?
It is returning the ASCII value of character 1
The first statement treats the argument as string and converts the value into Int, The second one treats the argument as char and returns its ascii value
As the others said, Convert returns the ASCII code.
If you want to convert '1'
to 1 (int)
you should use
int val = Convert.ToInt32('1'.ToString());
The code '1'
is the same as (char)49
(because the Unicode code point of the character 1
is 49). And Convert.ToInt32(char)
returns the code point of that character as an int
.
As others have already pointed out: In your second example ('1'
) you are using a char
literal. A char
is a numeric type. There is no parsing done as in the string example ("1"
), since it already is a number - just a cast to a wider number format (from 16 bits to 32 bits).
It treats '1' as char and int form of any char is its ASCII equivalent so it return its ASCII equivalent. But in case of "1" it treats it as string and convert it to integer.
精彩评论