简体   繁体   English

将十进制数转换为二进制的C#程序

[英]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. 因此,我必须制作一个将十进制数转换为二进制并打印它的程序,但不使用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 ? 我到了可以打印出数字的地步,但是相反(例如:12表示为0011而不是1100),任何人都知道如何解决该问题? 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 您实际上甚至不需要if语句

Instead of write them inmediately you may insert them in a StringBuidler 您可以将它们插入StringBuidler中,而不是立即编写它们

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

And then use that StringBuilder 然后使用该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. 因为使用%2确定位值时从最低有效数字开始,所以生成的数字相反。 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(); System.Text.StringBuilder反向=新的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#. 有更好的方法可以做到这一点,但这很容易理解为什么它可以修复您的代码-似乎您正在尝试学习C#。

If I'm not mistaken 如果我没错的话

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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