Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Numbers and Binary Data

Python int methods

Reference for Python int methods: bit_length(), bit_count(), to_bytes(), from_bytes(), as_integer_ratio(), is_integer() and conjugate(), with examples and pitfalls.

Python integers are objects, so they have methods. They are rarely used in everyday code, but they are handy for bit work, binary file formats and number theory. Python's int has no size limit, so these methods work on huge values too.

Call a method on a variable (n.bit_length()) or wrap a literal in parentheses or add a space: (255).bit_length(). Writing 255.bit_length() is a syntax error, because Python reads 255. as a float.

Python
n = 37
n.bit_length()   # 6
n.bit_count()    # 3

Try it

Python Counting bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Integers and bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Method Description
int.bit_length() Number of bits needed to represent the absolute value, without sign and leading zeros. 0 gives 0.
int.bit_count() Number of 1 bits in the absolute value (added in 3.10).
int.to_bytes(length=1, byteorder="big", *, signed=False) Returns a bytes object of exactly length bytes. Since 3.11 both length and byteorder have defaults.
int.from_bytes(bytes, byteorder="big", *, signed=False) Class method. Builds an int from a bytes-like object or an iterable of ints in 0..255.
int.as_integer_ratio() Returns (numerator, 1) as a tuple.
int.is_integer() Always True (added in 3.12, for symmetry with float).
int.conjugate(), .real, .imag, .numerator, .denominator Complex and rational protocol: real and numerator are the number itself, imag is 0 and denominator is 1.

Raises: OverflowError from to_bytes() if the value does not fit in length bytes, or if it is negative and signed=False. ValueError if byteorder is not "big" or "little".

Usage notes

  • bit_length() ignores the sign. (-37).bit_length() equals (37).bit_length().
  • Pick the byte count yourself. to_bytes() does not shrink automatically; compute (n.bit_length() + 7) // 8 as the minimum, remembering one extra bit for the sign when signed=True.
  • Byte order matters. Network protocols and many file formats use big-endian; sys.byteorder tells you your machine's native order.
  • from_bytes is called on the class, int.from_bytes(...), not on an instance.
  • bit_count() before 3.10 can be written as bin(n).count("1").
  • Methods return new values. Integers are immutable.
  • Floats have their own methods: see float methods.