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
| Parameter | Description |
|---|---|
x |
An integer (or an object with __index__()). |
Return value
A string such as '0b1010'.
Examples
print(bin(5))
print(bin(255))
print(bin(-3))
Output
0b101 0b11111111 -0b11
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
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
0bprefix, use formatting:format(n, "b")orf"{n:b}". - Convert back with
int("1010", 2).
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
hex()· Convert an integer to a lowercase hexadecimal string prefixed with 0x, such as hex(255) giving '0xff'.oct()· Convert an integer to an octal string prefixed with 0o, such as oct(8) giving '0o10'. Often used for file permissions.int()· Convert a number or string to an integer. Floats are truncated toward zero, and strings can be in any base from 2 to 36.format()· Format a single value with a format spec, such as format(3.14159, '.2f') giving '3.14'. The same mini-language as f-strings.- Python Numbers · tutorial