Вопрос

I am wanting to create an array of bitmasks of X length and am looking for an efficient function.

For length 3 I would like it to generate:

000, 001, 010, 011, 100, 101, 110, 111

I am looking for a solution that uses bit math to do so - right now I am just using regular for loops as my bit operations is rudimentary.

Это было полезно?

Решение

Did you try the following:

function range(til) {
    var x = 0, xs = [];
    while (x < til) xs.push(x++);
    return xs;
}

function generate(n) {
    return range(Math.pow(2, n));
}

Now you can generate all the numbers from 0 to 7 as follows:

var xs = generate(3);

If you want it in string format then use the following function instead:

function replicate(n, x) {
    var i = 0, xs = [];
    while(i++ < n) xs.push(x);
    return xs;
}

function generateBitmasks(n) {
    var padding = replicate(n, '0').join('');

    return range(Math.pow(2, n)).map(function (x) {
        return (padding + x.toString(2)).slice(-n);
    });
}

Now you can get the list of bitmasks for 0 to 7 as follows:

var bitmasks = generateBitmasks(3);

I hope that helped.

Другие советы

It's just this:

var length = 3, 
    limit = 1 << length;  //Shift length bytes to the left
for(mask=0; mask < limit; mask++){
   console.log(mask);  //This will log in decimal, but the bin value is correct
}

They're basically the binary representations of all numbers from 0 to 2^n-1

Hope this helps. Cheers

This is the same idea from Aadit M Shah, merged with Edgar Villegas Alvardo's.

// Pad with left 0's
function pad(val, width) {
  val = val + '';
  return val.length >= width ? val : new Array(width - n.length + 1).join('0') + val;
}

// Get a list of decimal numbers representing all the bitmasks up to the given length
function getBitmapDecimalList(length) {
    var bitmaskMax  = 1 << length;
    var bitmaskList = [];
    for (var i = 0; i < bitmaskMax; i++) {
        bitmaskList.push(i);
    }
    return bitmaskList;
}

// Get a list of strings representing all the bitmasks up to the given length
function getBitmapBinaryList(length) {
    var bitmaskMax  = 1 << length; // Shift operator, equivalent to Math.pow(2,length)
    var bitmaskList = [];
    for (var i = 0; i < bitmaskMax; i++) {
        // the `.toString(2)` is what transforms the number into a binary string
        var bitmaskBinary = Number(i).toString(2);
        var paddedBitmask = pad(bitmaskBinary, length);
        bitmaskList.push(paddedBitmask);
    }
    return bitmaskList;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top