Pinapleu
Pinapleu
CC#
Created by Pinapleu on 5/24/2023 in #help
❔ Converting from binary to integer
Recently I had to problem where I would convert an integer to binary and count the ones, the problem itself didn't have any issues, however, I noticed that of I converted binary 1 to an integer, it would become 49 and 0 be camera 48. This is the code: static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); string str = Convert.ToString(n, 2); char[] bin = str.ToCharArray(); int sum = 0; for(int i=0;i<bin.Length;i++) { if(bin[i]-48==1) { sum++; }
} Console.WriteLine(sum); } When doing Console.WriteLine(bin[i]) it outputs 1s and 0s but when comparing with 1 it's always different, then I noticed the 48-49 thing so I removed 48 from every number, making the code work, my question is, why does it become 48-49? Is it related to it being a char array?
18 replies