3

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.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.