Skip to main content

Bitwise in Javascript

Setting bitwise attributes

const attrA = 1 << 0; // 2^0 i.e. 0001
const attrB = 1 << 1; // 2^1 i.e. 0010
const attrC = 1 << 2; // 2^2 i.e. 0100
const attrD = 1 << 3; // 2^3 i.e. 1000

let flags = 0; // empty

// use | to add attributes
flags = flags | attrA; // or flags |= attrA
// 1 - i.e. 0000 | 0001 -> 0001
flags = flags | attrC;
// 5 - i.e. 0001 | 0100 -> 0101

// use ^ to remove attributes
flags = flags ^ attrA; // or flags ^= attrA;
// 4 - i.e. 0101 ^ 0001 -> 0100

Checking for attributes

Four possible cases:

// has a single attribute attrA - "&" is exclusionary
if (flags & attrA) {}

// has ANY of the attributes - "|" is inclusionary, "&" is exclusionary
if (flags & (attrA | attrC)) {}
// ^^^^^^^^^^^^^^^^^^^^^^ evaluates to a value >= 0

// has ONLY the specified attributes
if (flags === (attrA | attrC)) {}
// ^^^^^^^^^^^^^^^^^^^^^^^ evaluates to a boolean

// has ALL of the attributes
// i.e. the union of attributes can't supersede the flags alone, otherwise it
// has a bit that flags doesn't
if (flags === (flags | (attrA | attrC))) {}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluates to a boolean

Refs