Question

I have a function which will need to be passed an arbitrary number of bits, for example 7. Is there a straitforward way to calculate the largest number available with that number of bits. Eg, if I passed in 8, the function would return 255.

Is there a straightforward/effieicnt way to do this?

Était-ce utile?

La solution 2

You could just do (I'd say this is pretty straightforward and efficient):

def max_bits(b):
    return (2 ** b) - 1

Demo:

>>> max_bits(8)
255

This works since binary place values are always exponents of 2, so this is probably the simplest and easiest to understand.

Autres conseils

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!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top