JavaScript bitwise arithmetic

I finally got an opportunity yesterday to do something I’ve always wanted to do: use bitwise arithmetic in JavaScript. Why would I want to do that? Mostly because it’s interesting and different, but also because bit-twiddling is something that programmers should just know how to do, whether or not we ever actually have to anymore.

The problem with bitwise arithmetic in JavaScript (and, for that matter, in most other languages) is that it’s almost always the wrong solution to the problem. It’s not 1972 anymore, and we can spare enough RAM to give each boolean value its own variable. Sure, it’s a tiny bit less efficient, but the efficiency cost is more than offset by the increased readability and maintainability of code with meaningful variable names.

So in all but the most performance-critical examples, using bitwise arithmetic smacks of premature optimization and over-cleverness. So imagine my delight when I was given the task of storing at least 2, possibly more, flags in a single database field. We weren’t going to get a second field under any circumstances. Arguments raged about whether to use comma-delimited strings, JSON-encoded objects, pre-defined constants, or something else.

What I arrived at was, I believe, the correct solution given the problem. I’m using an integer to store the booleans, and each bit position in the int corresponds with a single flag. Checking the flags is where the fun comes in. Folks with heavy CS backgrounds are not going to be impressed, but those of us who have honed our skills in interpreted languages will get a kick out of this:

// Check whether the second bit is set in the passed integer
function checkFlag(bitmap){
    var mask = 2; // since 2 in binary is 00000010, this will check the second bit.
    return bitmap & mask
}

The bitwise AND operator (&) takes the bitmap and the mask (which is 00000010 in binary) and returns a new number where bits are only set to 1 if they are 1 in both the bitmap and the mask. So if you pass in 3 (00000011 in binary) as your bitmap, only the bit in the second position appears in both. The operator returns 0000010. Since it’s non-zero, we know it passed the test. If you pass in 4 (00000100 in binary), no bit gets set since no bit is set in both numbers. The operation returns 0, and we know the test failed.

So, given a tricky problem (store multiple boolean values in a single variable), we have a tricky solution that’s a little bit of fun to implement and think about. I would love to hear examples of other legitimate uses for clever JavaScript.

Post a comment.