Javascript 基于数字(JS)设置位数

Javascript 基于数字(JS)设置位数,javascript,Javascript,我正在编写一个简单的IP计算器,我需要一个JavaScript中的特定函数,这是我无法理解的 基于十进制数,它将创建一个位数等于该数字的数字 例如,数字3将创建0000 0111,数字7将创建0111111,等等。伪代码: NumberToBits(int x) { var answer = 2^x; if(x > 1) return answer + NumberToBits(x-1); } 伪代码: NumberToBits(i

我正在编写一个简单的IP计算器,我需要一个JavaScript中的特定函数,这是我无法理解的

基于十进制数,它将创建一个位数等于该数字的数字

例如,数字3将创建0000 0111,数字7将创建0111111,等等。

伪代码:

    NumberToBits(int x) {
    var answer = 2^x;
    if(x > 1)
        return answer + NumberToBits(x-1);
    }
伪代码:

    NumberToBits(int x) {
    var answer = 2^x;
    if(x > 1)
        return answer + NumberToBits(x-1);
    }

因为有前导零,所以我假设结果是一个字符串。你可以为此滥用:

function createSequence( ones, total ) {
  // create an array of the correct size
  return (new Array( total ))
  // add the zeros at the start
           .fill( 0, 0, total - ones )
  // add the ones at the end
           .fill( 1, total - ones )
  // stitch it all together
           .join( '' );
}

createSequence( 3, 8 );
// > "00000111"

createSequence( 7, 8 );
// > "01111111"

因为有前导零,所以我假设结果是一个字符串。你可以为此滥用:

function createSequence( ones, total ) {
  // create an array of the correct size
  return (new Array( total ))
  // add the zeros at the start
           .fill( 0, 0, total - ones )
  // add the ones at the end
           .fill( 1, total - ones )
  // stitch it all together
           .join( '' );
}

createSequence( 3, 8 );
// > "00000111"

createSequence( 7, 8 );
// > "01111111"

您还可以使用以下代码:

函数createSequence(个,总计){
var结果=(2**total+2**one-1).toString(2).切片(1);
console.log(结果)
返回结果;
}
createSequence(3,8);

createSequence(7,8)
您还可以使用以下代码:

函数createSequence(个,总计){
var结果=(2**total+2**one-1).toString(2).切片(1);
console.log(结果)
返回结果;
}
createSequence(3,8);

createSequence(7,8)
您需要根据数字递归执行2^x操作。例如,对于数字7,您需要一个执行2^7+2^6+2^5的算法。。。2^1您需要根据数字递归执行2^x操作。例如,对于数字7,您需要一个执行2^7+2^6+2^5的算法。。。谢谢你,这正是我需要的!谢谢,这正是我需要的!