cyberwombat
cyberwombat

Reputation: 40104

Enumerate through binary number bits in reverse

I currently have this loop that takes an integer and prints out 0 or 1 for each bit of it's binary version.

var m = 10;
for (var i = 0; i < 8; i++) {
  bit = m & 1;
  console.log(bit ? + 1 : 0 );
  m >>= 1;
}

This results in 0 1 0 1 0 0 0 0

How can I get it to loop in reverse? 0 0 0 0 1 0 1 0

Upvotes: 1

Views: 2418

Answers (2)

thefourtheye
thefourtheye

Reputation: 239493

If you like to hand-craft the whole binary representation implementation, then you can use Barmar's answer.

But, the good news is, there is a reliable, builtin function, Number.prototype.toString which you can use to do this, like this

var bin = (10).toString(2), numberOfBits = 8;
console.log((new Array(numberOfBits + 1).join("0") + bin).slice(bin.length));

Output

00001010

Upvotes: 2

Barmar
Barmar

Reputation: 781096

Iterate a bit mask rather than shifting bits of the integer.

for (var i = 7; i >= 0; i--) {
    bit = m & (1 << i);
    console.log(bit ? 1 : 0);
}

or:

for (var mask = 1 << 7; mask; mask >>= 1) {
    bit = m & mask;
    console.log(bit ? 1 : 0);
}

Upvotes: 3

Related Questions