Search code examples
pythonpython-2.7bit-manipulationbit

What is the best way to check if all bits are 1?


I thought this would be easy due to ~, but ~ just returns a negative value of 2^x rather than 0.


Solution

  • You can modify a standard bithack for checking if a number is a power of 2 (numbers one less than a power of 2 are all 1s), with a special case check for zero:

    def allOnes(n):
        return ((n+1) & n == 0) and (n!=0)
    
    print allOnes(255)
    print allOnes(158)
    print allOnes(0)
    print allOnes(-1)
    print allOnes(-2)
    

    Output:

    True
    False
    False
    True
    False