What is a bitmask

Bitmasks are omnipresent when we dig a little into how Linux works. Probably the most known bitmask is the IP4v subnet mask. This post explains what a bitmask is and how it works.

We use an analogy to understand what a bitmask is and why our computers would be a lot slower without them.

Assume we have a multiple choice test in school or university with 32 questions that can be answered either yes or no. It is our job to check them. If there are 100 students we would have to check 3200 answers one by one. A lot of work.

It would look like that.

Question 1: Answer: yes Correct Answer: yes Result: OK

Question 2: Answer: yes Correct Answer: no Result: not OK

Question 3: Answer: no Correct Answer: no Result: OK …

and so on.

We can make that a lot easier with a sample solution. When comparing both sheets with a light source shining through we can immediately see where they are different.

That is exactly what a bitmask does:

Correct Answers/Given Answers:

10010101110001011010101010101101
11010100110001011011101010101111

The Result has a one for those bits/questions that are different and a 0 for those bits that are equal. That operation is called a bitwise XOR.

01000001000000000001000000000010

That is actually a lot easier and the good thing is that the computer can process all 32 bits in one single step. A modern CPU can even do 64 bits at once so we could compare two tests at the same time (bit-level parallelism).

Normally, we do not encounter bitmasks as individual bits, but as hexadecimal, octal or decimal. In hexadecimal the above numbers are 0x95C5AAAD and 0xD4C5BAAF. And the result of a bitwise XOR is 0x41001002 then. Or we could split our 32 bits into single bytes and diplay each of them as decimal number. Then we have 65.0.10.2 as a result. That looks similar to what we do with IPv4 subnet masks.

It is not so obvious at all that the result of a bitwise XOR between 0x95C5AAAD and 0xD4C5BAAF is 65.0.10.2..Understanding what is going on a bit level often makes things a lot easier.

“There are only 10 types of people in the world – those who understand binary, and those who don’t.”

Contact