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

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


当前回答

这是我的代码:

var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";

function add(n) {
    if (n == 0) {
        binaryvar = "0" + binaryvar; 
    }
    else {
        binaryvar = "1" + binaryvar;
    }
}

function binary() {
    while (i < 1) {
        if (x == 1) {
            add(1);
            document.write(binaryvar);
            break;
        }
        else {
            if (x % 2 == 0) {
                x = x / 2;
                add(0);
            }
            else {
                x = (x - 1) / 2;
                add(1);
            }
        }
    }
}

binary();

其他回答

这是我常用的方法。这是一个非常快速和简洁的方法,适用于整数。

如果你愿意,这个方法也适用于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然后删除最后一位,并将倒数第二位作为新的最后一位。重复这个过程,直到所有的位都被读取。

当然,这是对实际情况的极端简化。我是这样概括的。

这是我的代码:

var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";

function add(n) {
    if (n == 0) {
        binaryvar = "0" + binaryvar; 
    }
    else {
        binaryvar = "1" + binaryvar;
    }
}

function binary() {
    while (i < 1) {
        if (x == 1) {
            add(1);
            document.write(binaryvar);
            break;
        }
        else {
            if (x % 2 == 0) {
                x = x / 2;
                add(0);
            }
            else {
                x = (x - 1) / 2;
                add(1);
            }
        }
    }
}

binary();

“convert to binary”中的二进制可以指三个主要的东西。位置数系统,内存中的二进制表示或32位位串。(64位位串参见Patrick Roberts的回答)

1. 数字系统

(123456). tostring(2)将数字转换为以2为基数的位置数字系统。在这个系统中,负数被写成负号,就像在十进制中一样。

2. 内部表示

数字的内部表示是64位浮点数,在这个答案中讨论了一些限制。没有简单的方法在javascript中创建一个比特字符串表示,也不能访问特定的位。

3.掩码和位操作符

MDN很好地概述了位操作符的工作方式。重要的是:

位操作符将其操作数视为32位序列(0和1)。

在应用操作之前,64位浮点数被转换为32位有符号整数。在它们被转换回来之后。

下面是将数字转换为32位字符串的MDN示例代码。

function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}

createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"

我用了一种不同的方法来解决这个问题。我决定在我的项目中不使用这段代码,但我想我会把它放在相关的地方,以防它对某人有用。

Doesn't use bit-shifting or two's complement coercion. You choose the number of bits that comes out (it checks for valid values of '8', '16', '32', but I suppose you could change that) You choose whether to treat it as a signed or unsigned integer. It will check for range issues given the combination of signed/unsigned and number of bits, though you'll want to improve the error handling. It also has the "reverse" version of the function which converts the bits back to the int. You'll need that since there's probably nothing else that will interpret this output :D

function intToBitString(input, size, unsigned) { if ([8, 16, 32].indexOf(size) == -1) { throw "invalid params"; } var min = unsigned ? 0 : - (2 ** size / 2); var limit = unsigned ? 2 ** size : 2 ** size / 2; if (!Number.isInteger(input) || input < min || input >= limit) { throw "out of range or not an int"; } if (!unsigned) { input += limit; } var binary = input.toString(2).replace(/^-/, ''); return binary.padStart(size, '0'); } function bitStringToInt(input, size, unsigned) { if ([8, 16, 32].indexOf(size) == -1) { throw "invalid params"; } input = parseInt(input, 2); if (!unsigned) { input -= 2 ** size / 2; } return input; } // EXAMPLES var res; console.log("(uint8)10"); res = intToBitString(10, 8, true); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(uint8)127"); res = intToBitString(127, 8, true); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(int8)127"); res = intToBitString(127, 8, false); console.log("intToBitString(res, 8, false)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, false)); console.log("---"); console.log("(int8)-128"); res = intToBitString(-128, 8, false); console.log("intToBitString(res, 8, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 8, true)); console.log("---"); console.log("(uint16)5000"); res = intToBitString(5000, 16, true); console.log("intToBitString(res, 16, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 16, true)); console.log("---"); console.log("(uint32)5000"); res = intToBitString(5000, 32, true); console.log("intToBitString(res, 32, true)"); console.log(res); console.log("reverse:", bitStringToInt(res, 32, true)); console.log("---");

试一试

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);
    }
}

我在这里得到了一些帮助