簡體   English   中英

有人可以向我解釋這個簡單的代碼嗎?

[英]Could someone explain this simple code to me please?

我只是想了解這段代碼。

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,然后將它們加在一起,這怎么給二進制數?

我們只輸入一些數據,好嗎?

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的余數) ),這是要打印的最右邊的數字。 將其余部分除以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!!

因此,您會看到,您的數字系統(二進制,八進制,十進制或十六進制等)只是寫下基數冪多項式的簡寫。 最右邊的數字始終為base ^ 0,向左移動的每個數字指數增加一。

獎勵積分,如果您知道小數點的作用;)

請參閱此頁面上的第二種方法: http : //www.wikihow.com/Convert-from-Decimal-to-Binary

這就是您的算法正在嘗試做的事情。

在十進制和二進制之間轉換時,請記住,每個二進制數字都是十進制2的冪。

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

因此,從右側開始,從整數構建二進制字符串:

  • 取小數和2的模數(數字的余數除以2)
  • 將結果追加到二進制字符串的左側
  • 將您的電話號碼除以2
  • 重復直到處理完所有數字

最后將該字符串轉換為數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM