简体   繁体   中英

adding 48 to string number

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

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" .

你看到的是ASCII代码'4'和'0'。

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

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

stringchars array ,所以,那就是为什么你收到这些结果,它基本上显示了'4'和'0'的ASCII

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM