简体   繁体   中英

C# Program that converts decimal number to binary

So, I have to make a program that converts a decimal number to binary and prints it, but without using Convert. I got to a point where I can print out the number, but it's in reverse(for example: 12 comes out as 0011 instead of 1100), anyone has an idea how to fix that ? Here's my code:

        Console.Write("Number = ");
        int n = int.Parse(Console.ReadLine());
        string counter = " ";


        do
        {

            if (n % 2 == 0)
            {                  
                counter = "0";
            }

            else if (n % 2 != 0)
            {
                 counter = "1";
            }

            Console.Write(counter);

            n = n / 2;
        }
        while (n >= 1);

simple solution would be to add them at the beginning:

Console.Write("Number = ");
int n = int.Parse(Console.ReadLine());
string counter = "";

while (n >= 1)
{
   counter = (n % 2) + counter;
   n = n / 2;
}
Console.Write(counter);

You actually don't even need the if statement

Instead of write them inmediately you may insert them in a StringBuidler

var sb = new StringBuilder();
....
sb.Insert(0, counter);

And then use that StringBuilder

var result = sb.ToString();

完成计算后可以反转字符串

You are generated the digits in the reverse order because you are starting with the least significiant digits when you use % 2 to determine the bit value. What you are doing is not bad though, as it is convenient way to determine the bits. All you have to do is reverse the output by collecting it until you have generated all of the bits then outputing everything in reverse order. ( I did not try to compile and run, may have a typo)

One easy solution is

System.Text.StringBuilder reversi = new System.Text.StringBuilder();

Then in your code replace

Console.Write(counter);

with

reversi.Append(counter);

Finally add the end of your loop, add code like this

string s = reversi.ToString();
for (int ii = s.Length-1; ii >= 0; --ii)
{
  Console.Write(s[ii]);
}

There are better ways to do this, but this is easy to understand why it fixes your code -- It looks like you are trying to learn C#.

If I'm not mistaken

int value = 8;
string binary = Convert.ToString(value, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM