Dec 23, 2016
There are often times when we want to represent the rights of access, and use on a specific resource, on a user by user basis. The most widely used culprit would be how we may want to represent user permissions on files and directories in a computer system. For cases like these, bitwise operators can be a great ally.
In computer science and many other engineering centric fields, we have access to many logical operators.
- & ( And )
- | ( Or )
- ^ ( XOR )
- ~ ( Binary Ones Compliment )
- « ( Left Shift )
- >> ( Right Shift )
These operators all allow us to manipulate the control flow of data. In our case, this data will be in the form of binary numbers.
For example, in the case of
& when both numbers contain a
1, the result in that place is
1, otherwise the value is
1001101 & 1100101 = 1000101
To forge a rudimentary permission system, we only need to understand
&, and maybe
>> for bit checking, but that’s outside the scope of this post.
Applying & To Permissions
If we treat each place in a string of binary numbers as an on/off switch for a given permission, we get something kind of like this…
[0/1] Read [0/1] Write [0/1] Execute
So, a user with read and write permissions may have a binary string that looks like so.
We may also assume that we have a file that has been given read only permissions.
If we use the
& operator, we can see which permissions exist both on the user and the file. In this case, they both have read!
101 // User & 100 // File = 100 // Result
Then before a read operation, we can check that the result contains the
1 in the position we expect, and bam, they have access!
Now, bitwise operators are not always an ideal approach for checking user permissions. Often times, the ways in which we determine access can be fairly complex, conditional, or based on the existence of other resources in a system. Still, it is always helpful to keep these concepts in the back of our heads for when the need presents itself.