bodokaiser
bodokaiser

Reputation: 15752

JavaScript set four bits

I got following bit pattern:

1000 0001 (129)

I now want to set the last four bits after my favor (1 - 10, 0x1 - 0xA):

1000 0010

or

1000 1000

I have actually no idea how I can accomplish this. I could read out the first four bits:

var buff = new Buffer(1);

buff[0] = 129;

var isFirstBitSet = (buff[0] & 128) == 128;
var isSecondBitSet = (buff[0] & 64) == 40;
var isThirdBitSet = (buff[0] & 32) === 32;
var isFourthBitSet = (buff[0] & 16) === 16;

var buff[0] = 0xA;

if (isFirstBitSet) {
    buff[0] = buff[0] & 128;
}

and map then on a new one but I think it is self explained that this is crap.

Upvotes: 2

Views: 1600

Answers (1)

Pointy
Pointy

Reputation: 413737

You can set the low four bits of an integer by first ANDing the integer with 0xfffffff0 and then ORing it with your four-bit value.

function setLowFour(n, lowFour) {
  return (n & 0xfffffff0) | (lowFour & 0xf);
}

Note that JavaScript doesn't really have an integer type. The bitwise operations force the values to be integers, but they're really still stored as floating point numbers.

edit — I think it actually works too :-) setLowFour(1025, 12) returns 1036. How's that for unit testing?

Upvotes: 6

Related Questions