What is BitMask

Bitmasks are very resource friendly means of storing settings. As we know that binary numbers are always read from right to left. This is zero based index so taking 1010 as an example bit 0 is off, 1 is on, bit 2 is off and bit 3 is on. This makes binary numbers ideal for use as “switches” to enable or disable certain facilities.

How to use Bitmask

A good example of bitmask usage is when setting the log levels for a particular service. For example, if you enable all the logging options for the SMTP service you will end up with the SMTPLog variable set to a value of 4382. Converting 4382 to its binary equivalent gives 1000100011110, that is bits 1, 2, 3, 4, 8 and 12 are all set.

For example say you had the number 7 and you wanted to see if bit 1 was set (bit numbering starts at 0 so this is the second digit from the right in the binary numbers), you would do this

?(7 AND 2) = 2

This would return True, because bit 1 in the number 7 (0111) is set (i.e. it’s a 1)


Real World Example

Let’s take an example of using bitmasking to store results, let’s say we’re running an employment agency and we want to store four properties about applicants, these being their sex, are they employed, can they drive and are they looking for full time employment.

We’ll assign some numbers to these “properties” of our clients

    Const IsFemale = 1
    Const IsEmployed = 2
    Const CanDrive = 4
    Const FullTime = 8

When we get a new applicant we ask them the relevant questions and assign the corresponding numbers.

Let’s say we get a new client Fred, he is Male, Employed, he can’t drive and he’s looking for full time work, that is

IsEmployed + FullTime (= 2 + 8 = 10)

We therefore store the number 10 against this client in the table (lets say in the AppProps field), later on we could do a bitwise comparison of our clients.

To find out who is employed, for Fred’s record we would get

?(AppProps and FullTime) = FullTime

Would return True, showing that he is employed, but let’s say the work involved required a woman, then

?(AppProps AND IsFemale) = IsFemale


Leave a Reply

You must be logged in to post a comment.