Last active
November 7, 2025 09:26
-
-
Save lichrot/620d6a00133a887f60879203e4d15860 to your computer and use it in GitHub Desktop.
Bitmasking in JavaScript || TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const FLAGS = { | |
| // 0b0001 << 0 => 0b0001 | |
| active: 1 << 0, | |
| // 0b0001 << 1 => 0b0010 | |
| read: 1 << 1, | |
| // 0b0001 << 2 => 0b0100 | |
| write: 1 << 2, | |
| // 0b0001 << 3 => 0b1000 | |
| parent: 1 << 3, | |
| }; | |
| // 0b0000 | |
| let userFlags = 0; | |
| /* Switch the given bit ON */ | |
| // 0b0000 | 0b0001 => 0b0001 | |
| userFlags |= FLAGS.active; | |
| // 0b0001 | 0b1000 => 0b1001 | |
| userFlags |= FLAGS.parent; | |
| /* Switch the given bit OFF */ | |
| // 0b1001 & (~0b0001 => 0b1110) => 0b1000 | |
| userFlags &= ~FLAGS.active; | |
| // 0b1000 & (~0b1000 => 0b0111) => 0b0000 | |
| userFlags &= ~FLAGS.parent; | |
| /* Toggle the given bit ON/OFF */ | |
| // 0b0000 ^ 0b0100 => 0b0100 | |
| userFlags ^= FLAGS.write; | |
| // 0b0100 ^ 0b0100 => 0b0000 | |
| userFlags ^= FLAGS.write; | |
| /* Check whether the given bit is ON */ | |
| // 0b0000 | 0b0001 | 0b0100 | 0b1000 => 0b1101 | |
| userFlags |= FLAGS.active | FLAGS.write | FLAGS.parent; | |
| // 0b1101 & 0b0010 => 0b0000 => 0 => falsy | |
| Boolean(userFlags & FLAGS.read); // false | |
| // 0b1101 | 0b0010 => 0b1111 | |
| userFlags |= FLAGS.read; | |
| // 0b1111 & 0b0010 => 0b0010 => 2 => truthy | |
| Boolean(userFlags & FLAGS.read); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment