How to set, clear, toggle and check a bit in JavaScript?
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.
To flip one or more bits, use binary XOR. In your case, the appropriate XOR mask is 1 shifted k bits to the left.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With