Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 952
Robin Rodricks Avatar asked Sep 17 '09 02:09

Robin Rodricks


People also ask

How do you set clear AND toggle a single bit?

Use the bitwise AND operator ( & ) to clear a bit. number &= ~(1UL << n); That will clear the n th bit of number . You must invert the bit string with the bitwise NOT operator ( ~ ), then AND it.

How do you flip a single bit?

To flip one or more bits, use binary XOR. In your case, the appropriate XOR mask is 1 shifted k bits to the left.


1 Answers

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.

like image 154
cletus Avatar answered Sep 20 '22 07:09

cletus