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}`); |
Combined Flags: 21 true true
What is Bitmasking in JavaScript ?
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.