2

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.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
bodokaiser
  • 15,122
  • 22
  • 97
  • 140
  • You wish to set bits, yes? Try the bit operators | and &. Use buff[0] |= 128 to set the first bit, and buff[0] &= ~128 to clear it. At least that's how I'd do it in C. – Refugnic Eternium Jan 07 '13 at 16:09
  • [This question](http://stackoverflow.com/questions/1436438) describes how to set a single bit, but it will also work with multiple bits if you set the mask appropriately. – Robert Harvey Jan 07 '13 at 16:10

1 Answers1

6

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?

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I learned programming far enough in the past that bitwise operations were a fairly basic part of the deal for everybody :-) – Pointy Jan 07 '13 at 16:12
  • @Pointy why is it actually required to use such a big integer like 0xffffff0 why can't I use 0x80? – bodokaiser Jan 07 '13 at 17:02
  • 1
    @kyogron the point is that you want to *keep* all the bits in the original number above the low 4 bits. If you've got a number like `254437` you want to make sure that setting the low 4 bits doesn't wipe out some higher bits. Now, if you know your numbers are always smaller, you don't need to worry about it, but it won't hurt anything to use the full 32-bit mask. – Pointy Jan 07 '13 at 17:08