bin()

bin(x)
Returns: str · Updated March 13, 2026 · Built-in Functions
built-in conversion binary numbers

The bin() function converts an integer to a binary string representation prefixed with 0b. It is the quickest way to get the binary representation of any integer in Python.

Syntax

bin(x)

Parameters

ParameterTypeDefaultDescription
xintAn integer to convert to binary. Floats will raise a TypeError.

Examples

Basic usage

# Convert an integer to binary
result = bin(10)
print(result)
# 0b1010

Using with other numbers

# Zero
print(bin(0))
# 0b0

# Negative numbers include the negative sign
print(bin(-10))
# -0b1010

# Large numbers work fine
print(bin(255))
# 0b11111111

Converting back to int

# The int() function can parse binary strings
binary_str = bin(42)
print(binary_str)
# 0b101010

# Parse it back using base 2
back_to_int = int(binary_str, 2)
print(back_to_int)
# 42

# Or use the prefix-agnostic approach
print(int('101010', 2))
# 42

Practical: Bit operations

# Check if a number is even using bitwise AND
num = 7
if num & 1:
    print(f"{num} is odd")
else:
    print(f"{num} is even")
# 7 is odd

# bin helps visualize what's happening
print(bin(7 & 1))
# 0b1 (truthy)

# Check specific bit positions
position = 2
bit_value = 4  # 2^2
number = 10

print(f"Is bit {position} set in {number}? {bool(number & bit_value)}")
# Is bit 2 set in 10? True

print(f"Binary of 10: {bin(10)}")
# Binary of 10: 0b1010

Working with byte data

# Convert a byte to its binary representation
byte_value = 0b11001010
print(bin(byte_value))
# 0b11001010

# Extract individual bits
for i in range(7, -1, -1):
    bit = (byte_value >> i) & 1
    print(bit, end='')
# 11001010

Common Patterns

Formatting without the prefix

# Remove the '0b' prefix
num = 42
binary_without_prefix = bin(num)[2:]  # Slice off '0b'
print(binary_without_prefix)
# 101010

# Pad to fixed width
print(bin(5)[2:].zfill(8))
# 00000101

Validation and checking

# Check if a number is a power of 2
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0

print(is_power_of_two(8))   # True
print(is_power_of_two(10))  # False
print(is_power_of_two(0))   # False

# Count set bits (population count)
def count_bits(n):
    return bin(n).count('1')

print(count_bits(255))  # 8
print(count_bits(7))    # 3

Errors

TypeError with non-integers

# This will raise TypeError
bin(3.14)
# TypeError: 'float' object cannot be interpreted as an integer

# Strings need conversion first
int("1010", 2)  # 10, then bin(10) works

Converting strings directly

# This raises ValueError
bin("1010")
# TypeError: object cannot be interpreted as an integer

# Convert string to int first
bin(int("1010", 2))
# 0b1010

See Also