Created
April 15, 2014 10:03
-
-
Save JohnArcher/10719520 to your computer and use it in GitHub Desktop.
How do you set, clear and toggle a single bit in JavaScript?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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