Store flags using bitwise operations
03 Apr 2023To store flags using bitwise operation in typeScript, you can create a function that takes a number representing the current flags state, a flag value to set or unset, and a boolean indicating whether to set or unset the flag. Here’s an example function:
function setFlag(currentFlags: number, flag: number): number {
return currentFlags | flag;
}
In the setFlag
function, we use the OR (|
) operator to set the flag value.
function clearFlag(currentFlags: number, flag: number): number {
return currentFlags & ~flag;
}
In the clearFlag
function, we use the AND (&
) and bitwise complement (~
) operators to unset the flag value.
function hasFlag(currentFlags: number, flag: number): boolean {
return (currentFlags & flag) !== 0;
}
In the hasFlag
function, we use the AND (&
) operator to check if the flag value is set.
// Define flag values as power of 2
const FLAG_A = 1; // 00000001
const FLAG_B = 2; // 00000010
const FLAG_C = 4; // 00000100
const FLAG_D = 8; // 00001000
let flags = 0;
// Set flag A and C
flags = setFlag(flags, FLAG_A);
flags = setFlag(flags, FLAG_C);
// Check if flag A is set
if (hasFlag(flags, FLAG_A)) {
console.log('Flag A is set');
}
// Unset flag C
flags = clearFlag(flags, FLAG_C);
// Check if flag C is unset
if (!hasFlag(flags, FLAG_C)) {
console.log('Flag C is unset');
}
// Set flag B and D
flags = setFlag(flags, FLAG_B);
flags = setFlag(flags, FLAG_D);
// Print the final flags state
console.log(`Flags state: ${flags}`); // should output 11 (00001011)
Here, we define four flag values as power of 2 to represent each flag. We start with an initial flags state of 0 and use the setFlag
function to set flags. We use the clearFlag
function to unset flags. We also use the hasFlag
function to check if the flag is set. Finally, we print the final flags state to the console.