Bit Masking: A Practical Example

How to store data on teeny-tiny bits

Constantin Stan
6 min readJul 9, 2020

--

All your base are belong to us

If you're a programmer, you may already have some notions of numeral systems and you've interacted with a couple of them.

If not, then it'll be a bit harder to feel at home going forward and it may help to get familiar:

For understanding the following example, it is very important to understand the binary system and its operators. In it, we’ll use only the & (AND) and ^ (XOR) operators. AND will be used to determine whether a particular bit is 1 or 0. XOR will be used to switch particular bits between 1 and 0.

There are 10 types of people in this world, those who understand binary and those who don’t.

The practical example

Our computers work with the binary system and that means that the digits that can be used at any given position are either 0 or 1.

The values of 0 and 1 can be considered to be false and true, and here things become interesting for the example we'll explore.

We’ll use bits to store a user’s email notifications settings. More exactly the binary representation of an integer.

For that, I created the following CodePen.

This is a clone of the CodePen's Email Notifications page. I’ll not explain the Flutter and Dart code that went into creating the UI. Instead, I’ll focus on what allows us to store a user’s email notifications preferences in binary within a single integer.

It all starts with creating a Flutter StatefulWidget. This type of widget provides methods to…

--

--

Recommended from Medium

Lists

See more recommendations