How do you set, clear and toggle a single bit in JavaScript?

Robin Rodricks picture Robin Rodricks · Sep 17, 2009 · Viewed 46.5k times · Source

How to set, clear, toggle and check a bit in JavaScript?

Answer

cletus picture cletus · Sep 17, 2009

To get a bit mask:

var mask = 1 << 5; // gets the 6th bit

To test if a bit is set:

if ((n & mask) != 0) {
  // bit is set
} else {
  // bit is not set
}

To set a bit:

n |= mask;

To clear a bit:

n &= ~mask;

To toggle a bit:

n ^= mask;

Refer to the Javascript bitwise operators.