A use case of Bitwise AND

15 / Apr / 2011 by Mohd Farid 5 comments

Recently, I used bitwise Anding in my grails project. I am sharing the approach that we followed by means of an example.

Suppose we have a domain class Person which can have multiple attributes like Smart, Intelligent, Talkative etc.

What sort of relationship comes to our mind when we see this?
I believe the obvious answer would be Person hasMany Attributes

Next, what if we want to optimize our design so that the searches on the Person becomes better.

Well, this was the question we were facing in our recent project where we finally used the bitwise AND.
We decided to have one field of type Long in our Person class. We named this as attributes . Soon, I ll be explaining why a long for Attribute…

We ensured that the Attributes are never going to be more than 20-30 . So, it became a nice candidate which could utilize the benefit of Bitwise ANDing.

We associated a binary weight to every instance of Attribute domain class.

The rows in the attribute table of our database looked somewhat like this

id | attribute      | weight
1 | Smart          | 1
2 | Talkative      | 2
3 | Intelligent     | 4
4 | Cooperative  | 8
5 | Ignorant       | 16

So, in order to save a Person who is Smart and Cooperative , we would set his attributes field.
weight of Smart + weight of Cooperative.
ie 1+8 = 9.

Suppose our Person table has some entries as follows:

id  | name  | attributes
1   | Tom   |  9
2   | Fred   |  12
3   | John   | 18

If we want to search a person who is Intelligent we need to have a final query like this

Select * from person where attributes&4 = 4
(4 is the weight of Attribute - Intelligent)

Search a person who is Cooperative and Talkative

Select * from person where attributes&2=2 and attributes&8=8
or more optimally,
Select * from person where attributes&10=10
(2 is the weight of Talkative and 8 is the weight of Cooperative)

Some points to be kept in mind before taking this approach:

There is a maximum limit of 64 values for the field on which we plan to do BitwiseANDing.
Bitwise AND is not directly supported by Hibernate, but we can add a custom function and dialect.

Hope this helped.

Thanks & Regards
Mohd Farid


comments (5)

  1. Mohd Farid

    Yes, This is a sql syntax.

    Hope this will help you in getting the correponding implementation for informix.

  2. Nate

    > Search a person who is Cooperative and Talkative
    > Select * from person where attributes&2=2 and attributes&8=8

    You could also do a single operation:

    Select * from person where attributes&10=10

    same effect, and only one comparison!


Leave a comment -