Reputation: 27996
I have a string in C# like this:
string only_number;
I assigned it a value = 40
When I check only_number[0]
, I get 52
When I check only_number[1]
, I get 48
why it is adding 48 to a character at current position? Please suggest
Upvotes: 2
Views: 1727
Reputation: 700690
It's not adding 48 to the character. What you see is the character code, and the characters for digits start at 48 in Unicode:
'0' = 48
'1' = 49
'2' = 50
'3' = 51
'4' = 52
'5' = 53
'6' = 54
'7' = 55
'8' = 56
'9' = 57
A string is a range of char
values, and each char
value is a 16 bit integer basically representing a code point in the Unicode character set.
When you read from only_number[0]
you get a char
value that is '4'
, and the character code for that is 52. So, what you have done is reading a character from the string, and then converted that to an integer before you display it.
So:
char c = only_number[0];
Console.WriteLine(c); // displays 4
int n = (int)only_number[0]; // cast to integer
Console.WriteLine(n); // displays 52
int m = only_number[0]; // the cast is not needed, but the value is cast anyway
Console.WriteLine(m); // displays 52
Upvotes: 3
Reputation: 48580
String is basically char[]
. So what you are seeing is ASCII value of char 4 and 0.
Proof: Diff between 4 and 0 = Diff between 52 and 48.
Since it is a string so you didn't assigned it 40. Instead you assigned it "40"
.
Upvotes: 8
Reputation: 19272
string
is the array
of chars
, so, that;s why you recieved these results, it basicallly display the ASCII
of '4' and '0'.
Upvotes: 1
Reputation: 33867
You are accessing this string and it is outputting the ASCII character codes for each of your two characters, '4' and '0' - please see here:
http://www.theasciicode.com.ar/ascii-control-characters/null-character-ascii-code-0.html
Upvotes: 2