Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 226
Pritam Avatar asked Jul 18 '26 18:07

Pritam


1 Answers

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.

like image 65
Jean-François Fabre Avatar answered Jul 21 '26 10:07

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!