❔ 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?
} 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?
16 Replies
Pobiega#2671
REPL Result: Success
Result: int
Compile: 315.382ms | Execution: 72.521ms | React with ❌ to remove this embed.
as we can see, the numerical value of
'1'
is actually... 49.Confusing, but, thanks
Pobiega#2671
REPL Result: Success
Result: char
Compile: 381.175ms | Execution: 23.567ms | React with ❌ to remove this embed.
😄
So it's because it's a char not an integer? Just like how letters have numbers assigned?
yes
Alright, thanks
A useful trick is to subtract
'0'
Tvde1#0587
REPL Result: Success
Result: int
Compile: 313.896ms | Execution: 23.718ms | React with ❌ to remove this embed.
this is not binary 😐
ASCII Table - ASCII Character Codes, HTML, Octal, Hex, Decimal
Ascii character table - What is ascii - Complete tables including hex, octal, html, decimal conversions
as u can see, character '1' represents 49 in ascii
subtract like that to get the actual integer
TheRanger#3357
REPL Result: Success
Result: int
Compile: 455.436ms | Execution: 25.022ms | React with ❌ to remove this embed.
also works
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.