C
C#2y ago
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?
16 Replies
MODiX
MODiX2y ago
Pobiega#2671
REPL Result: Success
(int)'1'
(int)'1'
Result: int
49
49
Compile: 315.382ms | Execution: 72.521ms | React with ❌ to remove this embed.
Pobiega
Pobiega2y ago
as we can see, the numerical value of '1' is actually... 49.
Pinapleu
PinapleuOP2y ago
Confusing, but, thanks
MODiX
MODiX2y ago
Pobiega#2671
REPL Result: Success
(char)1
(char)1
Result: char


Compile: 381.175ms | Execution: 23.567ms | React with ❌ to remove this embed.
Pobiega
Pobiega2y ago
😄
Pinapleu
PinapleuOP2y ago
So it's because it's a char not an integer? Just like how letters have numbers assigned?
Pobiega
Pobiega2y ago
yes
Pinapleu
PinapleuOP2y ago
Alright, thanks
Tvde1
Tvde12y ago
A useful trick is to subtract '0'
MODiX
MODiX2y ago
Tvde1#0587
REPL Result: Success
'5' - '0'
'5' - '0'
Result: int
5
5
Compile: 313.896ms | Execution: 23.718ms | React with ❌ to remove this embed.
Omnissiah
Omnissiah2y ago
this is not binary 😐
TheRanger
TheRanger2y ago
ASCII Table - ASCII Character Codes, HTML, Octal, Hex, Decimal
Ascii character table - What is ascii - Complete tables including hex, octal, html, decimal conversions
TheRanger
TheRanger2y ago
as u can see, character '1' represents 49 in ascii subtract like that to get the actual integer
MODiX
MODiX2y ago
TheRanger#3357
REPL Result: Success
(int)Char.GetNumericValue('1')
(int)Char.GetNumericValue('1')
Result: int
1
1
Compile: 455.436ms | Execution: 25.022ms | React with ❌ to remove this embed.
TheRanger
TheRanger2y ago
also works
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server