Skip to content

Instantly share code, notes, and snippets.

@JohnArcher
Created April 15, 2014 10:03
Show Gist options
  • Save JohnArcher/10719520 to your computer and use it in GitHub Desktop.
Save JohnArcher/10719520 to your computer and use it in GitHub Desktop.
How do you set, clear and toggle a single bit in JavaScript?
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 (https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators).
Source: http://stackoverflow.com/questions/1436438/how-do-you-set-clear-and-toggle-a-single-bit-in-javascript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment