pistacchio
pistacchio

Reputation: 58893

JavaScript set bits from the left

I have a number, for example 128. Its bit representation is 10000000. I want to set the 3rd bit from the left to have 10100000 (160).

I thought that I could do this with:

var foo = 128;
foo = foo | 1 << 2;

But this gives me 132 or 10000100. It set the 3rd from the right! How to set it from the left to 0 or to 1?

Upvotes: 2

Views: 122

Answers (3)

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

This worked:

var foo = 128;
foo = foo | foo >> 2

But what if you want to turn it on and off?

var foo = 128;
var mask = foo >> 2;

// Flick the bit on
foo = foo | mask;
// foo now equals 160

// Set the bit back to 0
foo = foo & ~mask;
// foo equals 128 again

Upvotes: 1

orlland
orlland

Reputation: 1266

function transformBits(bits, order, target) {
  var bitStr = bits
    .toString(2)
    .split('')
    .map(function(value, index) { 
      return index == (order - 1) ? target : value; 
    })
    .join('');

  return parseInt(bitStr, 2);
}

document.writeln(transformBits(128, 3, 1));
document.writeln(transformBits(128, 3, 0));

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 1362

Try this. >> will do work from right side shifting

var foo = 128;
foo = foo | foo >> 2;

Refrence for Bitwise operators

Upvotes: 2

Related Questions