pythonbit-manipulation

Get binary mask in python


What is the easiest/fastest way to get a int in python which can be represented by all ones in binary. This is for generating N bit masks.

E.g:

If total number of bits is 4, then binary '1111' or int 15
If total number of bits is 8 then, binary '1111 1111' or 255

I was under the impression ~0 is for that purpose, looks like that is not the case or I am missing something.


Solution

  • It is very easy to achieve with bit shifting:

    >>> (1<<4)-1
    15
    

    Shifting 4 times 1 to the left gives you 0b10000, subtract 1 you get 0b1111 aka 15.

    The int("1"*4,2) method is inefficient because it involves building a string and parsing it back.