0

我只是想理解这段代码。

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;
}

它是一个二进制转换器,它是如何工作的?我只是没有得到模数,十进制/ = 2,然后将它们加在一起,那如何给出二进制?

4

3 回答 3

3

让我们输入一些数据,好吗?

convert2binary(10)
-> remainder, final = 0
-> result = ""
-> NaN (= false)

loop:
Decimal > 0, so: remainder = Decimal % 2 (= 0) and Decimal /= 2 ( = 5)
result = remainder + result = 0 + ""
NaN = false
repeat:
Decimal > 0, so: remainder = Decimal % 2 (= 1) and Decimal /= 2 ( = 2)
result = remainder + result = "10"
NaN = false
repeat:
Decimal > 0, so: remainder = Decimal % 2 (= 0) and Decimal /= 2 ( = 1)
result = remainder + result = "010"
NaN = false
repeat:
Decimal > 0, so: remainder = Decimal % 2 (= 1) and Decimal /= 2 ( = 0)
result = remainder + result = "1010"
NaN = false
repeat: WHOOPS: Decimal == 0, so we return the final (int representation) of result.

现在,为什么这行得通?

基本上,在每次迭代中,您从数字右侧拆分出最后一个二进制数字(这是%2位)。由于您随后将其余部分除以 2(/=2位),因此您可以在循环中执行此操作。

每次迭代都会在数字多项式中为您提供一个连续的位置:

decimal(10) == 1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0 * 2^0 = binary(1010)

您也可以朝另一个方向发展:如果您想编写一个打印数字的十进制变体的方法,您可以用(将数字除以十的余数)int.ToString()拆分最后一位数字,这是最正确的 -% 10要打印的大多数数字。将其余部分除以 10,以便您可以重复十位、数百位等...

让我们试试这个!

int number = 123;
// this is equivalent to: (1 * 10^2) + (2 * 10^1) + (3 * 10^0)
int remainder = number % 10; // remainder = 3
number /= 10 // number = 12 (integer division!!)
result = remainder + ""; // result = "3"
// number is now: (1 * 10^1) + (2 * 10^0), because we divided by 10!
remainder = number % 10; // remainder = 2
number /= 10 // number = 1
result = remainder + result; // result = "23"
// number is now: (1 * 10^0)
remainder = number % 10; // remainder = 1
number /= 10 // number = 0 - we're going to STOP now!
result = remainder + result; // result = "123"
// yay! hurray!!

所以,你看,你的数字系统(无论是二进制、八进制、十进制、十六进制或其他)只是写下你的基数的多项式的简写。最右边的数字总是以 ^ 0 为底,每向左移动一个数字,指数就会增加 1。

如果您弄清楚小数点的作用,则可以加分;)

于 2012-04-17T14:26:51.620 回答
0

请参阅此页面上的第二种方法:http: //www.wikihow.com/Convert-from-Decimal-to-Binary

这就是您的算法正在尝试做的事情。

于 2012-04-17T14:25:00.703 回答
0

在十进制和二进制之间进行转换时,请记住每个二进制数字都是十进制的 2 的幂。

100110 = 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 1*2^1 + 0*2^0 = 38

所以从一个整数构建二进制字符串,从右边开始:

  • 取十进制数和 2 的模数(余数除以 2)
  • 将结果附加到二进制字符串的左侧
  • 将您的数字除以 2
  • 重复直到处理完整个数字

最后将该字符串转换为数字。

于 2012-04-17T14:34:30.817 回答