Use an f-string with the b format specifier (f"{n:b}" for raw bits like "101010", or f"{n:#b}" for "0b101010") or format(n, "b") to get a clean binary string without a prefix, reserving the built-in bin(n) function when you specifically want the "0b"-prefixed representation (such as "0b101010" or "-0b101010" for negative integers).
Basic Example
num = 42
# 1. Recommended (clean binary string WITHOUT '0b' prefix):
print(f"{num:b}") # Output: '101010'
print(format(num, "b")) # Output: '101010'
# 2. Zero-padded fixed-width binary (e.g., 8-bit byte or 16-bit word):
print(f"{num:08b}") # Output: '00101010'
print(f"{num:#010b}") # Output: '0b00101010' (total width 10 includes '0b')
# 3. Built-in bin() function (ALWAYS includes '0b' prefix):
print(bin(num)) # Output: '0b101010'
print(bin(-42)) # Output: '-0b101010'
Key Details & Edge Cases
- Negative numbers produce a minus sign (
"-101010"/"-0b101010"), NOT two’s complement:- Because Python integers have arbitrary precision (infinite sign bits),
bin(-5)returns"-0b101"andf"{-5:b}"returns"-101". - To get an $N$-bit two’s complement binary representation (e.g., 8-bit
-5$\rightarrow$"11111011"), mask with(1 << bits) - 1:n, bits = -5, 8 twos_comp = f"{n & ((1 << bits) - 1):0{bits}b}" print(twos_comp) # Output: '11111011'
- Because Python integers have arbitrary precision (infinite sign bits),
- Avoid
bin(n)[2:]slicing on signed integers:- While
bin(42)[2:]returns"101010", callingbin(-42)[2:]slices off"-0"and leaves a broken leading"b"("b101010"). Always usef"{n:b}"orformat(n, "b")instead of string slicing.
- While
- Zero-padding width with
(f"{42:#010b}"vs.f"{42:08b}"):- When combining
(alternate form'0b') with0padding, the width includes the 2 characters of'0b'—so an 8-bit value with'0b'requires width10(f"{42:#010b}"$\rightarrow$"0b00101010").
- When combining
- Grouping bits with underscores (
_format option):- Insert
_in the format specifier (f"{0xABCD:016_b}") to group bits into readable 4-bit nibbles:"1010_1011_1100_1101".
- Insert
- Converting a binary string back to an integer (
int(s, 2)):int("101010", 2)andint("0b101010", 2)both parse back to42.
Comparison of Integer-to-Binary Conversion Methods in Python
| Method | Example (n = 42) |
Example (n = -42) |
Supports Zero-Padding & Nibble Grouping? | Best Used When |
|---|---|---|---|---|
f"{n:b}" (Recommended) |
"101010" |
"-101010" |
Yes (f"{n:08b}", f"{n:08_b}") |
Inline string formatting, fixed-width bitfields, and clean unprefixed binary output. |
format(n, "b") |
"101010" |
"-101010" |
Yes (format(n, "08b")) |
Passing a converter function or dynamically constructing format specifiers. |
bin(n) |
"0b101010" |
"-0b101010" |
No (always unpadded with 0b prefix) |
Quick REPL inspection or debugging when you want explicit 0b base notation. |
f"{n & 0xFF:08b}" |
"00101010" |
"11010110" |
Yes (fixed bit-width mask) | Hardware registers, network protocols, and signed two’s-complement bit representations. |
You must log in or register to comment.
