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

JavascriptNumbersBit Manipulation

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - 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.

Solution 2 - Javascript

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);
}

Solution 3 - Javascript

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.

Solution 4 - Javascript

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);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobin RodricksView Question on Stackoverflow
Solution 1 - JavascriptcletusView Answer on Stackoverflow
Solution 2 - JavascriptunlocoView Answer on Stackoverflow
Solution 3 - JavascriptOleksii TrekhlebView Answer on Stackoverflow
Solution 4 - JavascriptTekTimmyView Answer on Stackoverflow