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.
bin(10) # '0b1010' bin(-5) # '-0b101'
Try it
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.
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
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 withformat(n, "b"), which handles the sign correctly. - Padding and grouping.
f"{n:08b}"pads to 8 digits, andf"{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)raisesTypeError. Convert withint()if you really mean the whole part. - Reverse conversion.
int("1010", 2)parses binary text, andint("0b1010", 0)accepts the prefix. - Counting bits.
int.bit_count()(Python 3.10+) is faster thanbin(n).count("1");int.bit_length()gives the number of bits needed. - Other bases. See
hex()for hexadecimal andoct()for octal.