Left-shift the number 1 by the number of bits, subtract one:
def max_bits(b):
return (1 << b) - 1
Demo:
>>> max_bits(8)
255
>>> max_bits(256)
115792089237316195423570985008687907853269984665640564039457584007913129639935L
Bitshifting is faster than using the exponent of 2:
>>> import timeit
>>> def max_bits_bitshift(b):
... return (1 << b) - 1
...
>>> def max_bits_exp(b):
... return (2 ** b) - 1
...
>>> timeit.timeit('f(256)', 'from __main__ import max_bits_exp as f')
2.767354965209961
>>> timeit.timeit('f(256)', 'from __main__ import max_bits_bitshift as f')
0.49823594093322754
That's more than 5 times faster for a 256-bit number!