Open source, coffee and us….


Using Bitmaps and Bitmasks

Having been wrestling with the refactoring of some existing android code written by third-parties, I was deliberating over some data structures that seemed very unwieldy and enhancement unfriendly.  This involved using a child table to my main data store to hold various flags to indicate some dynamic property of the main data that could be used for filtering a query.  There was nothing in these child tables apart from flag identifiers,  and as a result there is a need to build a complicated sql statement with an outer join and a set of OR predicates for each flag required (or not required).

It did not take too long to recognise this as an ideal candidate for refactoring to use bitmaps and bitmasks to achieve the requirements in a much simpler manner.

These were the steps I took:

  • Add an integer column called ‘flags’ to my main table
  • Create a class containing final static int Constants for each required flag where the values equate to binary orders, i.e. 1,2,4,8,16,32 etc. , bearing in mind there is a limit to the size of ints and therefore the number of values that can be stored.
  • To populate the flags field we just need to add together all of the required flag constants.
  • To add a new flag we just add the flag constant to the existing flags field
  • To remove a flag, we can subtract the flag constant
  • To check whether  any flag is set we just need to do a bitwise  comparison of the current value with the flag value, i.e. the flag is set if flag == (value | flag)
  • We can also check for flags that are not set by comparing the flag in a similar manner with a bitmask which equates to the sum of all the possible values minus the ones that we are checking against.

With such a structure, we can then construct a sql filter that consists of a single where clause, e.g. where Table.tags | bitmask = bitmask.

This then provides and elegant and flexible solution to the problem, that can easily form part of a more complex sql filtering requirement

Cheap Pills in International Sites

Cheap Pharmacyviagra uk buy buy in Europe

Cheap Pharmacycialis uk


Onlinelasix online


Cheaporder cheap viagra

PurchaseDrugs no Prescription EUROPE
or herevalacyclovirbuy propecia ukviagra australia and you can see more here australia pharmacy generic