© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
17 replies
Pinapleu

❔ 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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Converting String to an integer with a Hexadecimal Value
C#CC# / help
3y ago
Converting from DTO to DomainModel
C#CC# / help
2y ago
Moving integer from one form to another
C#CC# / help
2y ago