bin() is a built-in Python function that converts an integer to its binary string representation, prefixed with '0b' — a simple, readable way to inspect or manipulate binary values. In 2026, bin() remains essential across domains: bit manipulation in algorithms, debugging binary data, low-level programming, data science (feature binarization, bit flags), cryptography, and embedded systems — fast, zero-overhead, and universally available. It works only on integers (int), raising TypeError on floats/strings; for negative numbers, it returns '-0b...'.
Here’s a complete, practical guide to using bin() in Python: basic conversion, formatting options, real-world patterns (bitwise operations, earthquake data flags, binary feature engineering), and modern best practices with type hints, performance, alternatives (format, f-strings, NumPy), and integration with Dask/Polars/pandas.
Basic bin() usage — integer to binary string with '0b' prefix.
print(bin(10)) # '0b1010'
print(bin(255)) # '0b11111111'
print(bin(-42)) # '-0b101010'
print(bin(0)) # '0b0'
print(bin(1 << 10)) # '0b10000000000' (1024)
Formatting binary strings — remove prefix, pad, uppercase.
n = 42
# Remove '0b' prefix
print(bin(n)[2:]) # '101010'
# Pad with zeros to 8 bits
print(f"{n:08b}") # '00101010' (f-string)
print(format(n, '08b')) # same
# Pad to 32 bits with sign
print(f"{n:032b}") # '00000000000000000000000000101010'
# Uppercase hex equivalent (for comparison)
print(hex(n).upper()) # '0X2A'
print(f"{n:08X}") # '0000002A'
Real-world pattern: bitwise operations & binary feature engineering in earthquake data.
import pandas as pd
import numpy as np
# Sample earthquake flags (bit positions: 0=shallow, 1=strong, 2=tsunami risk)
df = pd.DataFrame({
'event_id': [1, 2, 3, 4],
'flags': [0b001, 0b011, 0b101, 0b111] # binary flags
})
# Extract individual bits using bin() or bit operations
df['is_shallow'] = df['flags'].apply(lambda x: bool(x & 1)) # bit 0
df['is_strong'] = df['flags'].apply(lambda x: bool(x & 2)) # bit 1
df['tsunami_risk'] = df['flags'].apply(lambda x: bool(x & 4)) # bit 2
# Binary string representation for debugging
df['flags_bin'] = df['flags'].apply(bin)
print(df[['event_id', 'flags', 'flags_bin', 'is_shallow', 'is_strong', 'tsunami_risk']])
# Vectorized with NumPy (faster)
flags = df['flags'].to_numpy()
df['is_shallow_np'] = flags & 1 > 0
df['is_strong_np'] = flags & 2 > 0
df['tsunami_np'] = flags & 4 > 0
Best practices for bin() in Python & data workflows. Use bin(n)[2:] — to strip '0b' prefix for clean binary strings. Modern tip: use f-strings — f"{n:08b}" for padding/formatting; faster & more readable than bin() + string ops. Prefer bit operations (&, |, ^, ~, <<, >>) — for actual binary logic; bin() mainly for inspection. Use in debugging — print(f"flags: {bin(flags):>10}") for aligned output. Handle negative numbers — bin(-n)[3:] for unsigned binary. Add type hints — def to_binary(n: int) -> str: return bin(n)[2:].zfill(8). Use NumPy np.binary_repr(n, width=8) — padded binary string for arrays. Use Polars pl.col('flags').cast(pl.Int64).bin() — upcoming binary string support. Use Dask — darr.map_blocks(lambda x: np.array([bin(xi)[2:] for xi in x])) for parallel bin. Profile performance — bin() is fast; avoid in tight loops on millions of items. Use int(binstr, 2) — reverse conversion from binary string. Use format(n, 'b') — alias for bin(n)[2:]. Use f"{n:b}" — no prefix, simplest formatting. Use bin(n).count('1') — popcount / Hamming weight. Use bin(n).index('1') — position of highest set bit.
bin() converts integers to binary strings with '0b' prefix — use for debugging, logging, bit inspection, or formatting. In 2026, prefer f-strings for padding/formatting, bit operations for logic, NumPy/Polars/Dask for vectorized/parallel use, and integrate with pandas pipelines. Master bin(), and you’ll handle binary representation cleanly and efficiently in any numerical or data workflow.
Next time you need to see a number in binary — use bin(). It’s Python’s cleanest way to say: “Show me this integer as bits — simple and readable.”