Time to Read: 1 minute, 42 seconds

Bitwise flags

01 Jun 2019 Share:  
Bitwise flags

Time to read: 1 minute, 42 seconds


One of the basic priciples in programming are bitwise operations. These are very fast operations and can help you doing all sorts of stuff and can help you write faster and more optimized code. Also combined with boolean evaluation routines and multiple checkboxes or multiple boolean attributes needed to be added to a record, you might consider using bitwise flags instead. Flags can be stored in a single integer. A 32-bit integer can store up to 31 flags or 31 boolean values.

In the example below 2 flags are set in Javascript and we want to check if flag 2 is added to setFlags

let flag1 = 1
let flag2 = 2
var setFlags = flag1 + flag2  // value = 3
if ( (setFlags & flag2) == flag2) { console.log("Flag 2 is added."); }

It is because of the AND operator written as "&" in Javascript that does the trick, but what does bitwise operator AND really do? AND returns all bits that are EQUAL on both sides of the equation. So in our case.

variables 8 4 2 1
flag 2 0 0 1 0
setFlags 0 0 1 1
& flag 2 0 0 1 0

Since we only check 1 flag the result in this case is 2 (when the flag exsists), and the result would be 0 (when it does not). Knowning this we could also write it as a "not equal" comparison. Making it even faster in subroutines then several flags need to be tested.

if ( (setFlags & flag2) != 0) { console.log("Flag 2 is added."); }

Next step instead of defining all the boolean variables its beter to create a Set of an Enumeration.

var myEnum = {
 left: 1,
 right: 2,
 top: 4,
 bottom: 8
}
var myEnumSet = myEnum.left | myEnum.right;
if (myEnumSet & myEnum.right) {  // right flag is set }

Note: In Javascript every value above 0 evaluates as true. This is not the case in strong typed languages. Just to understand the last line of code here.

Next Post Previous Post