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.
Eg:
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.
it's very easy to achieve with bit shifting:
>>> (1<<4)-1
15
shifting 4 times 1 to the left gives you 0b10000
, substract 1 you get 0b1111
aka 15
.
(the int("1"*4,2)
method is overkill because it involves building a string and parsing it back)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.