I just wanted to understand this bit of code.
static int convert2binary(int Decimal)
{
int remainder, final = 0;
string result = "";
bool NaN;
while (Decimal > 0)
{
remainder = Decimal % 2;
Decimal /= 2;
result = remainder + result;
NaN = int.TryParse(result, out final);
}
return final;
}
It’s a binary converter, how does it work exactly? I just don’t get the modulus, decimal /= 2 and then plus them both together, how does that give binary?
Let’s just input some data, OK?
Now, why does this work?
Basically, on each iteration, you split off the last binary digit from the right of your number (this is the
%2bit). Since you then divide the rest by 2 (the/=2bit), you can do this in a loop.Each iteration will give you a successive position in the numbers polynom:
You can go in the other direction too: If you wanted to write an
int.ToString()method for printing out the decimal variant of the number, you would split off the last digit with% 10(the remainder of dividing the number by ten) and that is the rightest-most digit to print. Divide the rest by 10 to so you can repeat for the tens position, the hundreds position etc…lets try this out!
So, you see, your number system (be it binary or octal or decimal or hexadecimal or whatever) is just shorthand for writing down a polynom of powers of your base. The right-most digit is always base^0, and the exponent increases by one for each digit you move left.
Bonus points if you figure out what the decimal point does 😉