Tip: use bitwise operators to store multiple values in one value

Bitwise operators (AND, OR, NOT, XOR) and especially the AND (&) operator is a wonderful way to store multiple values in to one value. Sounds illogical, but here’s how it works: values are stored as powers of two – 1, 2, 4, 8, 16, 32… This way  only  one byte of a binary presentation of a number changes when numbers are combined. And checking if a byte is 1 or 0 is very easy and fast with bitwise operators.

An example scenario: user management

Users  have different rights in CMS systems. Storing a ”yes”/”no” value for each possible user right is tiresome and adds a lot of fields in the database. It also makes building SQL clauses cumbersome and causes extra pain when a new field should be added. Storing all user rights in one number makes life easier and one of the biggest advantages is that bitwise operators work in SQL clauses too.

User rights:

1 = read data

2 = write data

4 = delete data

8 = create a new user

16 = change user rights

32 = delete a user

If user has read and write rights to the data, his user rights value is 1 (read) + 2 (write) = 3. If he also have rights to delete a user, his combined user rights value is 1+2+32 = 35.

So, how do I check if the user has a specific right? Use the bitwise operator & (AND)

var userRights = 35 //1+2+32
 var ADMIN_RIGHTS = 16

 //does user have rights

 if((userRights & WRITE_RIGHTS) == WRITE_RIGHTS) {
 // user has rights to write
trace("HAS RIGHTS")
 else {
 // user hasn't got  rights to write
trace("NO RIGHTS")

 if((userRights & ADMIN_RIGHTS) == ADMIN_RIGHTS) {
// user has rights to write

else {
 // user hasn't got  rights to write

The is one drawback: the number that stores values increases rapidly (of course). If you have 15 different values to store, the maximum value for the storing number is 32768. Usually that is quite enough, but 20 values would require bigger data types in the database.