Open In App

What is Bitmasking in JavaScript ?

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Bitmasking in JavaScript refers to the manipulation and usage of bitwise operators to work with the binary representations of numbers and It is a technique commonly used to optimize certain operations and save memory in various algorithms Bitwise operators in JavaScript operate on individual bits of binary representations of the numbers rather than their decimal representations.

The numbers are represented in binary form, which consists of 0s and 1s. Bitmasking allows you to manipulate specific bits of these binary representations using bitwise operators like AND, OR, XOR, NOT, left shift, and right shift.

Approaches

  • Representing a set of binary flags
  • Optimizing memory
  • Checking the presence or absence of elements

Approach 1: Representing a set of binary flags

This approach is commonly used to represent sets of flags where each flag can be either on or off.

 

Example:

Javascript




const flagA = 4;
const flagB = 3;
const flagC = 2;
  
const geek = flagA | flagB;
const isFlagAPresent = (geek & flagA) !== 0;
const isFlagCPresent = (geek & flagC) !== 0;
console.log(`Combined Flags: ${geek.toString(3)}`);
console.log(`${isFlagAPresent}`);
console.log(`${isFlagCPresent}`);


Output

Combined Flags: 21
true
true

Approach 2: Optimizing memory

You can use bit masking to store multiple boolean values in a single integer and save memory when dealing with large collections.

Example:

Javascript




const item = [true, false, true, true, false, true, false];
let bitmask = 0;
for (let i = 0; i < item.length; i++) {
    if (item[i]) {
        bitmask |= 1 << i;
    }
}
const geek = (bitmask & (1 << 2)) !== 0;
console.log("Bitmask:", bitmask);
console.log(geek);


Output

Bitmask: 45
true

Approach 3: Checking the presence or absence of elements

You can use bit masking to check the presence or absence of specific elements in a collection.

Example:

Javascript




const geek = [2, 8, 13, 9, 7, 13];
  
let bitmask = 0;
for (let i = 0; i < geek.length; i++) {
    bitmask |= 1 << geek[i];
}
const numberToCheck = 6;
const isNumberPresent =
    (bitmask & (1 << numberToCheck)) !== 0;
console.log(isNumberPresent);


Output

false



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads