任何人都可以通过将十进制数转换为二进制来解释此过程

时间:2015-08-31 16:42:07

标签: javascript binary decimal

我在互联网上寻找将十进制数转换为二进制数的方法。我在一些论坛上发现了这段代码。

var number = prompt("Type a number!") //Asks user to input a number
var converted = []; // creates an array with nothing in it

while(number>=1) { //While the number the user typed is over or equal to 1 its shoud loop
    converted.unshift(number%2); // takes the "number" and see if you can divid it by 2 and if theres any rest it puts a "1" otherwise "0"
    number = Math.floor(number/2); // Divides the number by 2, then starts over again
}

console.log(converted)

我并不完全理解所有内容,所以我对我认为代码片段的内容做了一些评论。但任何能够更详细解释的人呢?或者我认为代码的方式是否正确?

2 个答案:

答案 0 :(得分:1)

此代码基于将十进制数转换为二进制数的技术。

如果我取十进制数字。我将它除以2并得到余数,它将是0或1.一旦你将57一直分为0.你得到二进制数例如:

57/2 = 28 r 1; 28/2 = 14 r 0; 14/2 = 7 r 0; 7/2 = 3 r 1; 3/2 = 1 r 1; 1/2 = 0 r 1;

剩余部分是二进制数。对不起,如果它有点难以阅读。我绝对建议在纸上写出来。从最后一个剩余部分读到第一个,余数看起来像这样:111001

将其反转以使其正确。 array.unshift()可以这样做,或者你可以在while循环后使用array.push()然后使用array.reverse()。 Unshift()可能是一种更好的方法。

57十进制等于111001,你可以检查。

顺便说一下,只要你从十进制转换,这个算法适用于其他基础。或者至少据我所知。

我希望这会有所帮助。

答案 1 :(得分:0)

看起来你已经明白了它的主旨。

让我们以随机数开头:

6 ===  110b

现在让我们看看上面的方法是做什么的:

数字是geq而不是1,因此,让我们将数字的最后一位添加到输出

6%2 === 0 //output [0]

我们在将数字除以2之后使用的数字,这实际上只是将整个事物向右移位,现在是11b(来自原始110b)。 11b === 3,正如您所期望的那样。

您也可以将number % 2视为bit-wise AND操作(number & 1):

  110
&   1
-----
    0

只要需要,循环的其余部分只需执行相同的操作:找到当前状态的最后一位,将其添加到输出,移动当前状态。