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

很像这个问题,但是是针对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();

其他回答

一个简单的方法就是……

Number(42).toString(2);

// "101010"

函数 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的补数表示。

我是这样处理的:

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

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

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

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("---");

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

这是一个老问题,我认为这里有很好的解决方案,但没有解释这些聪明的解决方案的使用。

首先,我们需要理解一个数字可以是正数也可以是负数。 此外,JavaScript提供了一个MAX_SAFE_INTEGER常量,其值为9007199254740991。这个数字背后的原因是JavaScript使用IEEE 754中指定的双精度浮点格式数字,并且只能安全地表示-(2^53 - 1)和2^53 - 1之间的整数。

所以,现在我们知道了数字“安全”的范围。此外,JavaScript ES6有内置方法number . issafeinteger()来检查一个数字是否是一个安全的整数。

逻辑上,如果我们想用二进制表示一个数字n,这个数字需要53位,但是为了更好的表示,让我们使用7组8位= 56位,并使用padStart函数根据其符号将左侧填充为0或1。

接下来,我们需要处理正数和负数:正数左边加0,负数左边加1。同样,负数将需要一个二补表示。我们可以很容易地通过添加Number来解决这个问题。MAX_SAFE_INTEGER + 1的数字。

例如,我们想将-3表示为二进制,让我们假设Number。MAX_SAFE_INTEGER = 00000000 11111111 (255) then Number。MAX_SAFE_INTEGER + 1将是00000001 00000000(256)。现在让我们加上数字number。MAX_SAFE_INTEGER + 1 -3,这将是00000000 11111101(253),但正如我们所说,我们将在左侧填充1,如11111111 11111101(-3),这在二进制中表示-3。

另一种算法是我们在数字上加1然后像这样求符号的倒数-(-3 + 1)= 2这将是00000000 00000010(2)现在我们像这样求每一位11111111 11111101(-3)我们又得到了-3的二进制表示。

下面是这些算法的工作代码片段:

function dec2binA(n) { if (!Number.isSafeInteger(n)) throw new TypeError('n value must be a safe integer') if (n > 2**31) throw 'number too large. number should not be greater than 2**31' if (n < -1*(2**31)) throw 'number too far negative, number should not be lesser than 2**31' const bin = n < 0 ? Number.MAX_SAFE_INTEGER + 1 + n : n const signBit = n < 0 ? '1' : '0' return parseInt(bin, 10).toString(2) .padStart(56, signBit) .replace(/\B(?=(.{8})+(?!.))/g, ' ') } function dec2binB(n) { if (!Number.isSafeInteger(n)) throw new TypeError('n value must be a safe integer') if (n > 2**31) throw 'number too large. number should not be greater than 2**31' if (n < -1*(2**31)) throw 'number too far negative, number should not be lesser than 2**31' const bin = n < 0 ? -(1 + n) : n const signBit = n < 0 ? '1' : '0' return parseInt(bin, 10).toString(2) .replace(/[01]/g, d => +!+d) .padStart(56, signBit) .replace(/\B(?=(.{8})+(?!.))/g, ' ') } const a = -805306368 console.log(a) console.log('dec2binA:', dec2binA(a)) console.log('dec2binB:', dec2binB(a)) const b = -3 console.log(b) console.log('dec2binA:', dec2binA(b)) console.log('dec2binB:', dec2binB(b))