🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeHow to Convert Integer to Binary String in Python

To convert an integer into a binary string, you need a way to express its value with the digits zero and one. Python can return that string with a 0b prefix or as binary digits without the prefix.
I’ll compare those forms and show how to set a minimum width for the binary string.
TL;DR: Convert an Integer to Binary Text
Use bin(number) for binary text with a 0b prefix, or the b format specifier for digits without the prefix.
- bin(42) returns 0b101010.
- format(42, “b”) returns 101010.
- f”{42:08b}” returns 00101010, padded to at least eight characters.
What Is Integer-to-Binary Conversion?
Binary uses the digits zero and one to express integer values. A Python string can hold the display text while the source value remains available for arithmetic.
Choose bin() because its prefix can identify the base for a reader or parser.
Python’s bin() documentation and its format specification define the available forms. AskPython’s guides to the bin() function and format() function show related examples.
Convert an Integer to Ordinary Text
Python offers several ways to produce decimal text, and each suits a different place in a program.
| Method | Example in the demo | When it fits |
|---|---|---|
| str() | str(value) | Store or pass a basic decimal string |
| f-string | f”{value}” | Insert a value into surrounding text |
| %s formatting | “%s” % value | Maintain a string using older formatting syntax |
| Concatenation | “count=” + str(value) | Join short text fragments explicitly |
| format() | format(value, “d”) | Apply a format specification at runtime |
I ran python3 binary_conversion_demo.py and saw the f-string produce 42. The same transcript shows 42 from percent formatting and concatenation, even though those expressions build text differently.
Using f-strings
An f-string embeds an expression inside a string literal.
Using %s Formatting
The table compares placeholder forms with the exact results printed by the demo.
| Percent form | Use | Demo result |
|---|---|---|
| %s | Convert a value to text | 42 |
| %d | Format an integer as decimal | 42 |
| Tuple values | Supply positional values in order | count / 42 |
| Named mapping | Address values by key | count: 42 |
| %% | Print one literal percent sign | 42% |
String Concatenation with an Integer
String concatenation joins text fragments with the plus operator, so both operands must be strings. The demo catches the TypeError from a direct string-and-integer attempt, then uses str() to form a valid message.
The successful line prints 42 after its label. The plus operator adds no spaces or punctuation by itself, so include a separator in one of the fragments when a message needs it.
Advanced Formatting Options
Use format() when a specification is selected at runtime, such as a report whose base comes from a setting. The demo stores b in format_spec and prints 101010 from that choice.
| Formatting choice | Example spec | Output detail |
|---|---|---|
| Binary type | b | 101010 |
| Prefix and width | #010b | 0b00101010 |
| Right alignment | *>8d | ******42 |
| Decimal grouping | ,d | 1,234,567 |
| Binary grouping | _b | 10_1010 |
| Positive sign | +b | +101010 |
Keep permitted format codes in a short allowlist when they come from settings. The invalid-code example shows the ValueError returned by an unsupported option.
How to Convert an Integer to a Binary String Step by Step
The steps use 42 as a sample value and show code for each output option.
Step 1: Compare binary and decimal string forms
I ran the named file below to compare binary conversion, decimal string styles, padding, and two failure cases. Each label names the operation that produced its value.
value = 42
label = "count"
print(f"bin({value}) -> {bin(value)}")
print(f"zero -> {bin(0)}")
print(f"zero digits -> {format(0, 'b')}")
print(f"negative bin -> {bin(-value)}")
print(f"binary digits -> {format(value, 'b')}")
print(f"packed byte hex -> {value.to_bytes(1, 'big').hex()}")
print(f"two-byte big-endian -> {(258).to_bytes(2, 'big').hex()}")
print(f"two-byte little-endian -> {(258).to_bytes(2, 'little').hex()}")
print(f"f-string decimal -> {value}")
print(f"f-string binary -> {value:b}")
print(f"debug f-string -> {value=}")
print(f"repr f-string -> {label!r}")
print(f"literal braces -> {{value}}")
print("percent formatting -> %s" % value)
print("percent sign -> %s%%" % value)
print("tuple formatting -> %s / %s" % ("count", value))
print("%(label)s: %(value)d" % {"label": "count", "value": value})
print("decimal percent -> %d" % value)
print("concatenation -> " + str(value))
print(f"format decimal -> {format(value, 'd')}")
print(f"zero-padded binary -> {format(value, '08b')}")
print(f"wide binary -> {format(256, '08b')}")
print(f"prefix and width -> {format(value, '#010b')}")
print(f"aligned decimal -> {format(value, '*>8d')}")
print(f"grouped decimal -> {format(1234567, ',d')}")
print(f"grouped binary -> {format(value, '_b')}")
print(f"signed binary -> {format(value, '+b')}")
format_spec = "b"
print(f"runtime format -> {format(value, format_spec)}")
print(f"negative binary -> {format(-42, 'b')}")
print(f"parsed integer -> {int('101010', 2)}")
print(f"negative input -> {int('-101010', 2)}")
print(f"prefixed input -> {int('0b101010', 0)}")
print(f"spaced and grouped input -> {int(' 10_1010 ', 2)}")
print(f"unprefixed base-zero input -> {int('101010', 0)}")
try:
int("102", 2)
except ValueError as error:
print(f"invalid binary input -> {type(error).__name__}: {error}")
try:
int("", 2)
except ValueError as error:
print(f"empty binary input -> {type(error).__name__}: {error}")
width = 8
mask = (1 << width) - 1
print(f"8-bit mask -> {mask}")
masked = -42 & mask
print(f"masked value -> {masked}")
print(f"8-bit negative -> {format(masked, f'0{width}b')}")
print(f"signed byte hex -> {(-42).to_bytes(1, 'big', signed=True).hex()}")
try:
"count=" + value
except TypeError as error:
print(f"direct concatenation -> {type(error).__name__}: {error}")
try:
format(value, 'z')
except ValueError as error:
print(f"invalid format -> {type(error).__name__}: {error}")
Run python3 binary_conversion_demo.py to see the exact output from that file:
bin(42) -> 0b101010
zero -> 0b0
zero digits -> 0
negative bin -> -0b101010
binary digits -> 101010
packed byte hex -> 2a
two-byte big-endian -> 0102
two-byte little-endian -> 0201
f-string decimal -> 42
f-string binary -> 101010
debug f-string -> value=42
repr f-string -> 'count'
literal braces -> {value}
percent formatting -> 42
percent sign -> 42%
tuple formatting -> count / 42
count: 42
decimal percent -> 42
concatenation -> 42
format decimal -> 42
zero-padded binary -> 00101010
wide binary -> 100000000
prefix and width -> 0b00101010
aligned decimal -> ******42
grouped decimal -> 1,234,567
grouped binary -> 10_1010
signed binary -> +101010
runtime format -> 101010
negative binary -> -101010
parsed integer -> 42
negative input -> -42
prefixed input -> 42
spaced and grouped input -> 42
unprefixed base-zero input -> 101010
invalid binary input -> ValueError: invalid literal for int() with base 2: '102'
empty binary input -> ValueError: invalid literal for int() with base 2: ''
8-bit mask -> 255
masked value -> 214
8-bit negative -> 11010110
signed byte hex -> d6
direct concatenation -> TypeError: can only concatenate str (not "int") to str
invalid format -> ValueError: Negative zero coercion (z) not allowed in integer format specifier

The output labels each case. The final error lines are caught, so the demonstration exits with code 0.
Step 2: Set a minimum binary width
Width 8 with zero-fill produces 00101010 for 42 and 100000000 for 256, retaining every digit when a value needs more positions. The hash option adds a base prefix that also takes part of the field.
Step 3: Choose alignment and separators
The demo aligns 42 at the right edge with asterisks and shows left and centered markers as alternatives.
Common Binary Conversion Edge Cases
Use the table to match a binary-input or output symptom to a fix.
| Case | Symptom | Fix |
|---|---|---|
| Negative integer | A minus sign appears before the binary digits | Handle the sign separately when the destination expects unsigned bits |
| Binary input parsed as decimal | The returned integer has a different value | Pass base 2 to int() |