Updating Bitmasks Using Simple SQL Statement
An often useful technique for storing options is to use bit masking to identify if a particular option is enabled or disabled. A contrived example (and this is a poor example!) might be a ATM that allows control of what options are available to the user.
Eg.
1 – Chequing
2 – Savings
4 – Credit Card
8 – Line of Credit
etc…
The setting, if stored in a datastore, might be as follows:
Table: USER_OPTIONS
Column: AVAILABLE_DEP_OPTIONS NOT NULL int
To determine what options a user has, a single number is recorded that stores the bitmasked representation of the users settings. For example, a user who has Chequing only would have a value of 1 (binary: 1), a user with chequing+savings+line of credit would have a value of 13 (1101).
Now lets imagine we have 1 000 000 users and we want to disable credit card for all users. We could write a script that would select all users who have a particular known set and then update it with the new value. But this would mean we would have to determine the new value for every combination that is in use and script each possiblity. A simpler approach, and one that actually highlights the usefulness of bitwise operation would be a simple sql script that would disable the option for all users by flipping the associated bit on|off.
The bitwise operator ‘|’ will enable the bit and the bitwise ‘& ~’ will allow disabling. (~ is the same as NOT).
So.. for our example.. our script now reads as follows:
-- Disable Credit Cards
update USER_OPTIONS set AVAILABLE_DEP_OPTIONS = AVAILABLE_DEP_OPTIONS & ~4