Is there a python 3 funtion that will return the largest number of N
bits?
Example:
>>> print(largest_bitsize(8))
255
>>> print(largest_bitsize(16))
65535
Is there a python 3 funtion that will return the largest number of N
bits?
Example:
>>> print(largest_bitsize(8))
255
>>> print(largest_bitsize(16))
65535
I don't think there's a builtin one, but it's easy enough to write your own. 2^N is always the smallest number that requires N+1 bits, so (2^N)-1 must be the largest number that requires N bits.
def largest_bitsize(n):
return 2**n - 1
print(largest_bitsize(8))
#result: 255
print(largest_bitsize(16))
#result: 65535
print(largest_bitsize(64))
#result: 18446744073709551615
I also don't think there's a built-in func but you could write it out. Use a bit shift (as opposed to exponents) for even faster performance:
def largest_bitsize(b):
return (1 << b) - 1
How about this?
def largest_bitsize(n):
return int('1' * n, 2)
Examples:
>>> int('1'*16, 2)
65535
>>> int('1'*64, 2)
18446744073709551615
@Kevin's answer costs O(log n) in time complexity due to the use of the power operator.
A more efficient way to calculate the largest number of n
bits would be to use bitwise shift and negation instead, which costs O(1):
def largest_bitsize(n):
return ~(-1 << n)
Here's a less efficient way to do this:
def largest_bitsize( n ):
return sum( [ 2 ** i for i in range( n ) ] )
I think there is not any BuiltIn is available. But you can try this..
def largest_bitsize(b):
return (2**b) - 1
Output:-
>>> largest_bitsize(64)
18446744073709551615