In Python, bin(x) converts an integer to a binary string that starts with the prefix 0b: bin(10) returns '0b1010'. Negative numbers get a minus sign in front: bin(-5) is '-0b101'.
The result is text, useful for displaying and debugging bits. To do arithmetic, keep working with the int. Convert back with int(text, 2), and use format() or f-strings when you need padding or no prefix.
bin() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Pass an int; you get a string back.
python
text = bin(number) # '0b...'
Call
What it does
bin(10)
Returns '0b1010'.
bin(-5)
Returns '-0b101' (sign and magnitude, not two's complement).
format(10, "08b")
Returns '00001010': padded, no prefix.
int("1010", 2)
Returns 10: back from binary text.
Sister functions: oct() gives 0o octal text and hex() gives 0x hexadecimal text.
Library declarations
python
bin(x, /)
# x: int, or an object with __index__()
Parameters
Parameter
Description
x
Required. An int (including bool) or an object that defines __index__().
Return Value
Return Value
Description
str
Binary digits prefixed with 0b (or -0b for negatives).
Python Examples
Example 1 — Binary Strings for Several Integers
Print the binary form of small, large, and negative integers.
python
for n in [0, 5, 10, 255, -5]:
print(n, bin(n))
Output
0 0b0
5 0b101
10 0b1010
255 0b11111111
-5 -0b101
How It Works
Zero.bin(0) is '0b0', never an empty string.
Place values. 5 is 4 + 1, so its bits are 101; 10 is 8 + 2, so 1010.
A full byte. 255 is the largest 8-bit value, eight 1 bits.
Negative sign. -5 is written as -0b101: the sign goes before the prefix.
Example 2 — Remove the Prefix, Pad, and Parse Back
Compare slicing, format(), and f-strings for clean binary text, then convert it back with int().
permissions: 0b101
can write? False
ones in 200: 3
bits needed for 200: 8
bin() accepts integers only
How It Works
Binary literals.0b100 is just the int 4; the prefix is how you type binary in Python source.
Combine and test.READ | EXECUTE sets two bits; & WRITE is 0, so bool() reports False.
Count the ones. 200 is 0b11001000; counting the character "1" gives 3 set bits.
Bit length and floats.bit_length() confirms 8 bits are needed; bin(3.0) raises TypeError.
Frequently Asked Questions
Call bin(n), for example bin(10) returns '0b1010'. Use format(n, "b") for the digits without the prefix.
Use format(n, "b") or f"{n:b}". Slicing bin(n)[2:] also works, but not for negative numbers.
Use format(n, "08b") or f"{n:08b}". For example format(5, "08b") is '00000101'.
Use int("1010", 2), which returns 10. int("0b1010", 0) also works and detects the prefix.
Python ints have no fixed width, so bin() shows a minus sign and the magnitude. Mask to a width first, such as bin(-5 & 0xFF), to see the 8-bit pattern.