More on Using Bitwise Operations
Learn how we can use bitwise operations to calculate bitmasks and do optimizations for arithmetic calculations.
We'll cover the following
Computing bitmasks
Here is another example of using bitwise operations. We need them for computing bitmasks, which use OR or AND operators to encode or decode values respectively. We’re already familiar with file permission masks in the Unix environment. Let’s suppose that a file has the permissions “-rw-r–r–”. It looks like this in binary:
0000 0110 0100 0100
Let’s suppose that we want to check if the file owner can execute it. We can do that by calculating the bitwise AND for the permission mask and the 0000 0001 0000 0000 0000
number. Here is the calculation:
0000 0110 0100 0100 & 0000 0001 0000 0000 = 0000 0000 0000 0000 = 0
The result equals zero. This means that the owner cannot execute the file.
Using the bitwise OR, we can set bits of the bitmask. For example, we can allow the owner to execute the file like this:
0000 0110 0100 0100 | 0000 0001 0000 0000 = 0000 0111 0100 0100 = -rwxr--r--
The lowest order bit is on the right and the highest order bit is on the left.
We performed the bitwise OR for the permission mask and the 0000 0001 0000 0000
number. The eighth bit of the number equals one. It changes the eighth bit of the permission mask. The corresponding bit in the mask can have any value. It does not matter because the bitwise OR sets it to one regardless of its current value. If we do not want to change some bits in the permission mask, we set the corresponding bits of the number to zero.
The bitwise AND clears bits of the bitmask. For example, let’s remove the file owner’s permission to write. Here is the calculation:
0000 0111 0100 0100 & 1111 1101 1111 1111 = 0000 0101 0100 0100 = -r-xr--r--
We set the ninth bit of the permission mask to zero. To do that, we should calculate the bitwise AND for the permission mask and the 1111 1101 1111 1111
number. The ninth bit of the number equals zero and all other bits are ones. Therefore, the bitwise AND changes only the ninth bit of the permission mask.
The OS operates masks whenever we access a file. This way, it checks our access rights.
Multiplication and division by a power of two
Here is the last example of using bitwise operations. Until recently, software developers used bit shifts as an alternative to multiplication and division by a power of two. For example, a bit shift to the left by two bits corresponds to multiplication by 22, i.e. 4. We can check this behavior with the following Bash command:
$ echo $((3 << 2))
12
Run the commands discussed in this lesson in the terminal below.
Get hands-on with 1400+ tech skills courses.