Something I use a lot on the server side is bitwise comparison. I find this especially useful when executing a search on SQL Server where you want to allow a user to select multiple values to search on. Not only is it more flexible but it way more efficient.


As an example say we have on our client application in Angular a multi-select list of items which denote an age range that a user can select from which is stored in our database as shown below.

The age range is stored along with a user entity. So for example we might have (shown in json notation) the following:

{FirstName: James,LastName: Coenen-Eyre, AgeRange: 2}

If we want to find all users in the age range 19-30 we would have to check for all rows with an age range of 2.

In SQL this would be:

Select * from Users where AgeRange = 2

The Problem

But what if we want to find all users with an age range of 19-30 and 31-40. Our SQL query immediately gets more complex:

Select * from Users where AgeRange = 2 or AgeRange = 3


Select * from Users where AgeRange between 2 and 3

The alternative using Between is a little better but only works if we are looking for contiguous age ranges and still means we would need to pass multiple values across the wire from our Angular client to our back end.

The Solution

To make this more flexible I include in my lists a BitValue as shown below:

If I stored the BitValue with the AgeRange rather than the Id then I only need to pass one value across the wire which is the sum of the BitValues and use this in my query. It could be a LINQ query or a SQL Query on the back-end.

Here's an example. Suppose we want to find all users in the age ranges 0-18, 31-40 and 61-65. Our SQL Query would look like this (where @AgeRange is the sum of selected items BitValues):

select * from Users where (AgeRange & @AgeRange) > 0


Hopefully that explains the concept sufficiently and you can see the value. Of course there are limitations. The sum of your BitValues cannot be larger than the max value of datatype that your AgeRange stores. For this reason I define this as 64 bit values to give me as much room as possible and this limits you to roughly 60 items in your list. Still not bad.

But what about Javascript?

Ok so if you want to do this in javascript then there is a little trick. For this example we have a function that determines if a Tab is in the list of tabs that should be displayed.

You might think the following will work:

function showTab(tabId){return AppService.currentPageTabs & tabId > 0;}

What we need to do is this:

function showTab(tabId){return ((AppService.currentPageTabs|0) & (tabId|0)) === (tabId|0);}

This is because according to the ECMAScript specification, the return values from bitwise operations must be 32-bit integers so we need to convert to an integer using a no-op binary or (| 0) and we need all those brackets.