我希望看到二进制形式的正整数或负整数。
很像这个问题,但是是针对JavaScript的。
我希望看到二进制形式的正整数或负整数。
很像这个问题,但是是针对JavaScript的。
当前回答
还有一个选择
const decToBin = dec => {
let bin = '';
let f = false;
while (!f) {
bin = bin + (dec % 2);
dec = Math.trunc(dec / 2);
if (dec === 0 ) f = true;
}
return bin.split("").reverse().join("");
}
console.log(decToBin(0));
console.log(decToBin(1));
console.log(decToBin(2));
console.log(decToBin(3));
console.log(decToBin(4));
console.log(decToBin(5));
console.log(decToBin(6));
其他回答
这是我常用的方法。这是一个非常快速和简洁的方法,适用于整数。
如果你愿意,这个方法也适用于bigint。你只需要把每个1变成1n。
// Assuming {num} is a whole number
function toBin(num){
let str = "";
do {
str = `${num & 1}${str}`;
num >>= 1;
} while(num);
return str
}
解释
这个方法,在某种程度上,遍历数字的所有位,就好像它已经是一个二进制数。
它以一个空字符串开始,然后将最后一位放在前面。Num & 1将返回数字的最后一位(1或0)。Num >>= 1然后删除最后一位,并将倒数第二位作为新的最后一位。重复这个过程,直到所有的位都被读取。
当然,这是对实际情况的极端简化。我是这样概括的。
您可以编写自己的函数来返回一个比特数组。 示例如何将数字转换为比特
除数|被除数|位/余数
2 | | 1
2 4 | | 0
2 | 2 | 0
~ | | ~ 1
上面一行的例子:2 * 4 = 8,余数为1 9 = 1 0 0 1
function numToBit(num){
var number = num
var result = []
while(number >= 1 ){
result.unshift(Math.floor(number%2))
number = number/2
}
return result
}
从下往上读余数。数字1从中间到上面。
还有一个选择
const decToBin = dec => {
let bin = '';
let f = false;
while (!f) {
bin = bin + (dec % 2);
dec = Math.trunc(dec / 2);
if (dec === 0 ) f = true;
}
return bin.split("").reverse().join("");
}
console.log(decToBin(0));
console.log(decToBin(1));
console.log(decToBin(2));
console.log(decToBin(3));
console.log(decToBin(4));
console.log(decToBin(5));
console.log(decToBin(6));
我们还可以计算正数或负数的二进制,如下所示:
函数toBinary (n) { Let binary = ""; 如果(n < 0) { N = N >>> 0; } while(Math.ceil(n/2) > 0){ 二进制= n%2 +二进制; n = Math.floor(n/2); } 返回二进制; } console.log (toBinary (7)); console.log (toBinary (7));
这就是解。事实上,这很简单
function binaries(num1){
var str = num1.toString(2)
return(console.log('The binary form of ' + num1 + ' is: ' + str))
}
binaries(3
)
/*
According to MDN, Number.prototype.toString() overrides
Object.prototype.toString() with the useful distinction that you can
pass in a single integer argument. This argument is an optional radix,
numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to
get a string representation of the binary for the base 10 number 100,
i.e. 1100100.
*/