Convenience function to determine the number of bytes needed for a specified integer (split into multiple lines for clarity's sake ... could just as easily be a one-liner).
If this is already a defined function within Python, please let me know--a quick web search turned up nothing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import math
def int_to_bytes_needed(integer):
bytes_needed = math.pow((integer + 1),.125)/2
rounded_bytes_to_whole = math.ceil(bytes_needed)
return rounded_bytes_to_whole
# One-liner versoins:
# required_bytes = lambda x: ((((x+1)**.125)/2)//1)+1
# required_bytes(INTEGER_GOES_HERE)
# or:
# ((((INTEGER_GOES_HERE +1 )**.125)/2)//1) + 1
|
From Python 3.1, integers have a bit_length() method:
See http://docs.python.org/3.4/library/stdtypes.html#int.bit_length
Thank you. That is precisely what I wanted.