Friday, November 19, 2010

Bitmasks, how the fuck do they work?

This was an actual question I was asked when I suggested "Use a bitmask" as a solution to a messy option list problem.

The Scenario:
The web service (or whatever) you are communicating with has a load of options that can be toggled on and off for a particular resource/operation/whatever. The somewhat basic design comes back as specifying in the JSON (I'm going to stop adding the whatever now mmkay) that you set these like so...

 {  
  "thing" : {  
    "option1" : "true",  
    "option2" : "false",  
    "option3: : "true",  
 ....  
  }  
 }  

Which looks fine enough except that when there is a lot of these options its both a pain setting them up before you send and its not really that efficient data transmission wise.

Instead think about using a bitmask. First there is the spec. (This is using C/C++/Obj C)

 typedef enum {  
  Option1 = 0,  
  Option2 = 1 << 0,  
  Option3 = 1 << 1,  
  Option4 = 1 << 2  
 } OptionTypes  

If you are using some other language you could have a hash/dictionary/associative array etc. where we are increasing the count in base 2 such as...

 OptionTypes = {  
  "Option1" = 1,  
  "Option2" = 2,  
  "Option3" = 4,
  "Option4" = 8,  
 ...  
 }  

Then to define the set of options in use you just use a BITWISE OR and test for options in use with a BITWISE AND.

 // set  
 myOptionSet = (Option1 | Option2 | Option4);  

 // test  
 if(myOptionSet & Option1) doOptionOneThing;  
 if(myOptionSet & Option2) doOptionTwoThing;  
 ...  

Which can be sent to the web service with a single integer value.

 // assuming 1,2 and 4
 {  
  "thing" : {  
    "options" : 11,  
 ....  
  }  
 }  

Simples.

0 comments: