I haven’t been able to find anything about this on the forum,so I’m posting a new thread.
I’m trying to read part of the name of the object and set each character to an integer. It’s a string of four single-digit numerical characters. When I try to convert, I think I’m getting the Unicode character instead of the single-digit integer. How can I convert it so that I get the single-digit integer?
Code:
Using System;
//...
for(int i = 0; i<4; i++)
{
//right edge is EdgeValues[0]; bottom edge is EdgeValues[3]
EdgeValues[i] = Convert.ToInt32(name[3+i]);
Debug.Log(EdgeValues[i]);
}
Output is:
08_2132 //name
50
49
51
50
I think you want to use Int32.Parse instead of Convert.
Yep Parse/TryParse is the way to go. There’s also another cute way which is:
char c = name[n];
int number = (int)(c - '0');
But this only works if you know for sure it’s in the range of 0-9 ASCII characters.
Just to add a bit more information, the ASCII character “0” has the ordinal value 48. that’s why you get the values
50 - 2
49 - 1
51 - 3
50 - 2
If you’re wondering why 48, the ASCII table has a quite clever layout, just not with decimal values but hexadecimal.
Numbers start at 0x30.
Upper case letters start at 0x41. That way the lowest 5 bits of the ascii code corresponds to 1=A, 2=B, …
Lower case letters start at 0x61 with the same logic as the upper case letters.
Uppercase letters start with 010xxxxx while lowercase letters start with 011xxxxx where xxxxx is the one-based index of the letter. Printable characters start at 0x20 (or 32 decimal) which is the space character. Codes below 32 are control characters like newline (0x0A or ‘\n’), carriage return (0x0D or ‘\r’), tab (0x09 or ‘\t’).
That’s how “strings” essentially work. Of course nowadays we usually use UTF8 strings where single characters can be represented by more than 1 byte. However UTF8 is backwards compatible to ASCII. So the characters 0-127 are the same in ASCII and UTF8.