Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python bin() function

Reference for Python bin(): convert an integer to a binary string with the 0b prefix, handle negatives, strip the prefix, pad with format() and use __index__.

The built-in bin() function converts an integer to a string of binary digits prefixed with 0b. The result is valid Python source for the same number, so 0b1010 is the integer ten.

Negative numbers get a minus sign in front (-0b101); Python does not show two's complement. For padding, grouping or a missing prefix, use format() or an f-string instead.

Python
bin(10)     # '0b1010'
bin(-5)     # '-0b101'

Try it

Python Binary strings

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 Counting and testing 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.

Syntax

Python
bin(x)
Name Description
x An int, or an object whose __index__() method returns an int.

Return value: a str such as '0b1010'; negative numbers start with '-0b'.

Raises: TypeError if x is not an integer and has no __index__() method (for example a float or a string).

Usage notes

  • Prefix. Strip it with slicing (bin(n)[2:]; wrong for negatives) or avoid it with format(n, "b"), which handles the sign correctly.
  • Padding and grouping. f"{n:08b}" pads to 8 digits, and f"{n:_b}" groups digits in fours with underscores.
  • Negative numbers are shown as a sign plus the magnitude. To see a fixed-width two's complement pattern, mask first: bin(n & 0xFF).
  • Floats are rejected. bin(3.5) raises TypeError. Convert with int() if you really mean the whole part.
  • Reverse conversion. int("1010", 2) parses binary text, and int("0b1010", 0) accepts the prefix.
  • Counting bits. int.bit_count() (Python 3.10+) is faster than bin(n).count("1"); int.bit_length() gives the number of bits needed.
  • Other bases. See hex() for hexadecimal and oct() for octal.