eloleon
eloleon

Reputation: 1254

Javascript bitwise mask

Does anyone ever attempted to get a binary 'components' of a number?

What I'm trying to do is:

I have number: 5, so it is 0101 in binary. I'm trying find a sum of what numbers could give us 5. Obviously I know it is 1 and 4 ( 0001 and 0100 ) but I can't figure out way of getting that via code.

MDN has nice article on Bitwise Operators but still no joy.

Upvotes: 0

Views: 175

Answers (3)

user663031
user663031

Reputation:

Here's a generator-based solution that will yield a series of ones or zeroes:

const bits = *(n) => { do yield n & 1; while (n >>= 1); };

> console.log(Array.from(bits(5));
< [1, 0, 1]

You could then multiply the results by the corresponding powers of two, and or filter out zeroes, if you are so inclined.

Upvotes: 0

James Long
James Long

Reputation: 4736

You can use Number.prototype.toString with a radix parameter.

var number = 5;
number.toString(2); // -> "101"

You can split that string and map using Number if you need the numbers themselves.

number.toString(2).split("").map(Number); // -> [1, 0, 1]

Just be sure to wrap the number in brackets if you don't want to store it as a variable first.

5.toString(2).split("").map(Number); // -> SyntaxError
(5).toString(2).split("").map(Number); // -> [1, 0, 1]

Upvotes: 0

JJJ
JJJ

Reputation: 33153

var number = 5, 
    result = [];

for(var i = 1; i <= number; i = i << 1) {
  if(i & number) {
    result.push(i & number);
  }
}

console.log(result);

The loop increments i in powers of two (1, 2, 4, 8...) using a bitwise shift (i << 1 multiplies the number by two, you could also do i *= 2) and checks with bitwise AND (&) if the original number has that bit set. If so, it adds it as a number to the result array.

Upvotes: 2

Related Questions