How to set, clear, toggle and check a bit in JavaScript?
Asked
Active
Viewed 7.1k times
99
-
@user JavaScript and C/C++ are different languages. Very helpful to have different answers from them both. – cmac Mar 09 '17 at 20:00
4 Answers
268
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.

om-nom-nom
- 62,329
- 13
- 183
- 228

cletus
- 616,129
- 168
- 910
- 942
37
I want to add some things (with thanks to @cletus)
function bit_test(num, bit){
return ((num>>bit) % 2 != 0)
}
function bit_set(num, bit){
return num | 1<<bit;
}
function bit_clear(num, bit){
return num & ~(1<<bit);
}
function bit_toggle(num, bit){
return bit_test(num, bit) ? bit_clear(num, bit) : bit_set(num, bit);
}

unloco
- 6,928
- 2
- 47
- 58
-
2This is great thanks. Can you explain why bit_test works? I understand the right shift to move the interesting bit to the rightmost position, but I get lost trying to understand what the intermediate value is and why its remainder when divided by 2 is nonzero when set. – Raoul Nov 15 '14 at 14:49
-
2After you get the wanted bit to rightmost position, you simply test if the new value is impair (new_value % 2 != 0). An impair number will have bit0 = 1 or else bit0 = 0 (because bit0 weight is 2 to power 0 which is 1) – unloco Nov 16 '14 at 11:19
-
3
-
1Yes, I have a french background. I used the french word for "odd" (couldn't edit to correct my comment) – unloco Jun 28 '18 at 12:43
-
1Do you have similar functions for testing numbers beyond the 32-bit range? – birwin Oct 24 '18 at 20:43
24
Get Bit
function getBit(number, bitPosition) {
return (number & (1 << bitPosition)) === 0 ? 0 : 1;
}
Set Bit
function setBit(number, bitPosition) {
return number | (1 << bitPosition);
}
Clear Bit
function clearBit(number, bitPosition) {
const mask = ~(1 << bitPosition);
return number & mask;
}
Update Bit
function updateBit(number, bitPosition, bitValue) {
const bitValueNormalized = bitValue ? 1 : 0;
const clearMask = ~(1 << bitPosition);
return (number & clearMask) | (bitValueNormalized << bitPosition);
}
Examples has been taken from JavaScript Algorithms and Data Structures repository.

Oleksii Trekhleb
- 2,543
- 20
- 22
6
I built a BitSet class with the help of @cletus information:
function BitSet() {
this.n = 0;
}
BitSet.prototype.set = function(p) {
this.n |= (1 << p);
}
BitSet.prototype.test = function(p) {
return (this.n & (1 << p)) !== 0;
}
BitSet.prototype.clear = function(p) {
this.n &= ~(1 << p);
}
BitSet.prototype.toggle = function(p) {
this.n ^= (1 << p);
}

TekTimmy
- 3,066
- 2
- 29
- 33