我希望看到二进制形式的正整数或负整数。

很像这个问题,但是是针对JavaScript的。


当前回答

这就是解。事实上,这很简单

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.
        */

其他回答

试一试

num.toString(2);

2是基数,可以是2到36之间的任何底数

源在这里

更新:

这将只适用于正数,Javascript表示负二进制整数在两个补符号。我做了这个小函数,我还没有正确地测试它:

function dec2Bin(dec)
{
    if(dec >= 0) {
        return dec.toString(2);
    }
    else {
        /* Here you could represent the number in 2s compliment but this is not what 
           JS uses as its not sure how many bits are in your number range. There are 
           some suggestions https://stackoverflow.com/questions/10936600/javascript-decimal-to-binary-64-bit 
        */
        return (~dec).toString(2);
    }
}

我在这里得到了一些帮助

我们还可以计算正数或负数的二进制,如下所示:

函数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));

函数 dec2bin(dec) { return (dec >>> 0).toString(2); } console.log(dec2bin(1));1 console.log(dec2bin(-1));11111111111111111111111111111111 控制台.log(dec2bin(256));100000000 console.log(dec2bin(-256));11111111111111111111111100000000

您可以使用Number.toString(2)函数,但它在表示负数时存在一些问题。例如,(-1). tostring(2)输出为“-1”。

要解决这个问题,可以使用无符号右移位操作符(>>>)将数字强制转换为无符号整数。

如果你运行(-1 >>> 0). tostring(2),你将把你的数字向右移动0位,这不会改变数字本身,但它将表示为一个无符号整数。上面的代码将正确地输出“111111111111111111111111111111111111111111111111”。

这个问题有进一步的解释。

-3 >>> 0(右逻辑移位)将其参数强制为无符号整数,这就是为什么你得到了-3的32位2的补数表示。

你可以使用递归解决方案:

函数intToBinary(number, res = "") { If (number < 1) If (res === "")返回"0" 其他的 返回res 否则返回intToBinary(数学。楼层(数目/ 2),数目% 2 + res) } console.log (intToBinary (12)) console.log (intToBinary (546)) console.log (intToBinary (0)) console.log (intToBinary (125)) 只对正数有效。

我是这样处理的:

const decbin = nbr => {
  if(nbr < 0){
     nbr = 0xFFFFFFFF + nbr + 1
  }
  return parseInt(nbr, 10).toString(2)
};

从这个链接获得:https://locutus.io/php/math/decbin/