Python 3 reference · Built-in Functions

Python bin() Function

Convert an integer to a binary string prefixed with 0b, such as bin(5) giving '0b101'. Negative numbers get a minus sign.

Python 3 Since 3.0

Syntax

bin(x)

Parameters

ParameterDescription
x An integer (or an object with __index__()).

Return value

A string such as '0b1010'.

Examples

Basic useTry it yourself
print(bin(5))
print(bin(255))
print(bin(-3))

Output

0b101
0b11111111
-0b11
Without the prefix, padded, and backTry it yourself
n = 10
print(f"{n:b}")    # without the 0b prefix
print(f"{n:08b}")  # padded to 8 digits
print(int("1010", 2))  # and back again

Output

1010
00001010
10
Count the 1 bitsTry it yourself
flags = 0b0110
print(bin(flags).count("1"), "bits set")
print(flags.bit_count())  # the same, faster

Output

2 bits set
2

Good to know

  • To drop the 0b prefix, use formatting: format(n, "b") or f"{n:b}".
  • Convert back with int("1010", 2).

Version history

VersionChange
Python 3.0Added