views:

574

answers:

3

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

+1  A: 

The same way. Most of the C operators work in JavaScript as well.

binarycoder
+10  A: 

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.

cletus
A: 

Use ^ exclusive or operator.

adatapost