Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 16 lines
 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

2 comments

Paul Moore 8 years, 2 months ago  # | flag

From Python 3.1, integers have a bit_length() method:

>>> n = 12
>>> n.bit_length()
4

See http://docs.python.org/3.4/library/stdtypes.html#int.bit_length

teddy_k (author) 8 years, 2 months ago  # | flag

Thank you. That is precisely what I wanted.