Python: How to Construct a Bit Mask?

April 6, 2017


It is a great fun to explore the Python language. Do we actually know the best way to write Python code? Let us consider the following example: we are giving an integer 'i', we want to find the bit mask of that length. For example, if 'i' is 3, we need '111' as the output; if 'i' is 5, we need '11111'. What is the best / Pythonic way to write the code?


Because there are so many ways to do this, I am just listing 3 of them as below (platform: PYNQ-Z1, Jupyter Notebook, Python 3.6; the source code is highlighted using this tool):

The final block checks whether the results are identical. Now, what do you think is the best code?


At first glance, you may expect type 1 is the slowest, and you expect type 2 and type 3 may end up with very similar results. You may guess type 2 and 3 would get interpreted by the compiler into the same machine code. The actual results are:

So the intuition on type 1 method is correct. However, as you can see, for type 2 and type 3, bit-shifting is still faster than power operations. The results tell us that we should use bit-shift operations as much as possible to avoid integer multiplication / power operations.