0
I am expecting for the output to be '1' , but instead it gives me '49'.Can someone explain what is happening in my code thanks:)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sololearn { class Program { static void Main(string[] args) { string b = "11"; int g = Convert.ToInt32(b[1]); Console.Write(g); } } }
2 Answers
+ 4
char '1' is 49
When you tried to convert 1 into an integer you produced the ascii result
https://code.sololearn.com/c7S4Mxsbwa9l/?ref=app
+ 2
b[ 1 ] gives you a `char`. When a `char` is converted to `int`, the ASCII code is used as value in calculation.
To get 1 you can subtract by char '0' (represents ASCII value 48).
int g = Convert.ToInt32( b[ 1 ] - '0' );