DEV Community

Discussion on: Explain bitwise operator Like I'm Five

Collapse
 
dmfay profile image
Dian Fay

How often do you need to perform operations on individual bits? This is more the stuff of lower-level languages like C and C++; they do turn up in JavaScript but it's quite rare that they're needed.

One common use for bitwise operators is in defining and checking bitmasks. This frequently comes up with the concept of permissions: PostgreSQL needs to know if a user can select from a table, insert into it, update records, and so forth. Each of these is a simple boolean flag on its own, but there are several of them, and when you consider that each user may have a different permission set for each table, it's a lot to keep track of.

Bitmasks consolidate these flags into a single value by assigning each flag one bit. The first four permissions look like this:

#define ACL_INSERT      (1<<0)  /* for relations */
#define ACL_SELECT      (1<<1)
#define ACL_UPDATE      (1<<2)
#define ACL_DELETE      (1<<3)
Enter fullscreen mode Exit fullscreen mode

A user-table permission set is then rolled up into a single number. Continuing with these first four, we might see a value like this:

   bit: 8 4 2 1
on/off: 1 0 1 1
Enter fullscreen mode Exit fullscreen mode

A user with this permission set can insert (1<<0 = the 1 bit), select (1<<1 = the 2 bit -- shifted left by one), and delete records. Expressed as an integer, the value of this nybble (half a byte) is eleven, which is a lot easier to throw around than four independent variables.

Checking permissions is also easy with a bitmask: just perform a bitwise and (&) between the bitmask and the permission you're checking. Let's test whether the user can perform a select:

        bit: 8 4 2 1
 user value: 1 0 1 1
 perm value: 0 0 1 0
bitwise and: 0 0 1 0
Enter fullscreen mode Exit fullscreen mode

Since a bit has to be 'on' in both to appear in the result, the user has access if and only if the result of the bitwise and equals the value of the permission being tested.