Built-in function

bin()

Converts a whole number to a binary string that starts with 0b, such as 0b1010 for 10. Use int(text, 2) to convert back.

BeginnerEvery example below runs in your browser. Change the code and press Run.

bin(x)

Computers store numbers in binary: only the digits 0 and 1. bin() shows you a whole number written that way, as a string. bin(5) is '0b101': the 0b prefix marks the text as binary.

It is useful for learning how numbers are stored, for working with flags packed into single bits, and for checking puzzles and bit tricks.

Negative numbers get a minus sign in front: bin(-5) is '-0b101'. To drop the prefix or pad with zeros, use format() with "b" instead.

Parameters

ParameterWhat it is
x
required
A whole number (int). Floats are not accepted.

Return value

A string starting with 0b (or -0b for negative numbers).

Examples

1Numbers in binary

Pythoneditable
for n in [0, 1, 2, 5, 10, 255]:
    print(n, bin(n))
Output
0 0b0
1 0b1
2 0b10
5 0b101
10 0b1010
255 0b11111111

2Without the prefix, with padding

Slicing off the first two characters works for positive numbers; format() is cleaner and can pad to a fixed width.

Pythoneditable
n = 10
print(bin(n)[2:])
print(format(n, "b"))
print(format(n, "08b"))
print(f"{n:#010b}")
Output
1010
1010
00001010
0b00001010

3Back from binary to a number

Pythoneditable
print(int("1010", 2))
print(int("0b1010", 2))
print(0b1010)
Output
10
10
10

int(text, 2) reads text as base 2. You can also type binary numbers in code with the 0b prefix.

4Count the 1 bits

Pythoneditable
for n in [7, 8, 255]:
    print(n, bin(n), bin(n).count("1"))
Output
7 0b111 3
8 0b1000 1
255 0b11111111 8

5Flags packed in one number

Each bit can stand for one yes/no setting. | switches bits on, & tests them.

Pythoneditable
READ = 0b100
WRITE = 0b010
RUN = 0b001

rights = READ | WRITE
print(bin(rights))
print("can write:", rights & WRITE != 0)
print("can run:", rights & RUN != 0)
Output
0b110
can write: True
can run: False

Common mistakes

Slicing [2:] on a negative number

bin(-5)[2:] gives 'b101', because the string starts with -0b. Use format(abs(n), "b") or handle the sign yourself.

Pythoneditable
n = -5
print(bin(n)[2:])
print(format(n, "b"))
Output
b101
-101

Passing a float or a string

bin(2.5) and bin("5") raise TypeError. Convert to a whole number first with int().

Pythoneditable
try:
    bin("5")
except TypeError:
    print("TypeError: bin() needs an int")
print(bin(int("5")))
Output
TypeError: bin() needs an int
0b101

Questions people ask

How do I convert binary to decimal in Python?

int("1010", 2) gives 10. The second argument is the base.

How do I get a fixed number of binary digits?

format(n, "08b") pads to 8 digits with zeros: format(5, "08b") is '00000101'.

How do I count the 1 bits faster?

From Python 3.10 on, n.bit_count() does it directly: (255).bit_count() is 8.

Spotted a mistake on this page? Tell us