Integer Methods

int.bit_length()

Measure the minimum number of binary digits needed for the magnitude, ignoring the sign and leading zeros. Zero returns 0. For a positive magnitude n, the result k satisfies 2**(k-1) <= n < 2**k. For a nonnegative integer, (k+7)//8 gives its minimum unsigned byte length; a signed encoding may require an extra bit.

Formal Syntax & Structure

python syntaxpython
value.bit_length()

Return Value

int

Number of magnitude bits.

Working Example

Example Snippetpython
value = 1024print(value.bit_length())print((-value).bit_length())print((value.bit_length() + 7) // 8)
Python Reference