让我们输入一些数据,好吗?
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。
如果您弄清楚小数点的作用,则可以加分;)