Convert int to binary string in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The fastest way to convert an integer to a binary string in Python is bin(n), which returns a string like '0b101101'. For a cleaner output without the 0b prefix, use format(n, 'b') or the equivalent f-string f'{n:b}'. For fixed-width binary with leading zeros, use a width specifier like f'{n:08b}'. This article covers all the built-in approaches, negative number handling, two's complement conversion, and manual implementations for learning purposes.
Built-In Methods
Python provides three built-in ways to convert an integer to its binary representation. They differ only in formatting.
When to Use Each
| Method | Output | Best For |
bin(n) | '0b101101' | Debugging, REPL inspection, when prefix is expected |
format(n, 'b') | '101101' | String building, logging, display |
f'{n:b}' | '101101' | Inline string formatting |
All three handle arbitrarily large integers because Python integers have no fixed bit width.
Fixed Width with Leading Zeros
When displaying byte values, bit masks, or protocol fields, you typically need a fixed number of digits:
The format specifier 08b means: pad with zeros to 8 characters wide, format as binary. This is more readable and reliable than manually prepending zeros with zfill():
Negative Numbers
This is where most developers get confused. Python integers are arbitrary precision, so there is no fixed bit width. bin(-5) returns the sign plus the magnitude, not a two's complement pattern:
Two's Complement Conversion
If you need a fixed-width two's complement representation (the way hardware actually stores negative integers), you must mask the value to the desired width:
The bitwise AND with a mask (0xFF for 8 bits, 0xFFFF for 16 bits) forces Python to produce the two's complement representation at that width.
Converting Two's Complement Back to Signed
To interpret a two's complement binary string as a signed integer:
Converting Binary Strings Back to Integers
The built-in int() function parses binary strings:
The second argument specifies the base. Use 2 for binary, 8 for octal, 16 for hexadecimal.
Manual Conversion: Division Method
For understanding the algorithm behind binary conversion, the repeated division method builds the binary string from least significant to most significant bit:
Each iteration extracts the remainder when dividing by 2 (the current least significant bit), then integer-divides by 2 to shift right. The bits are collected in reverse order and then reversed at the end.
Manual Conversion: Bitwise Method
The same conversion using bitwise operations instead of arithmetic:
This version is logically identical to the division method but uses & 1 (bitwise AND) instead of % 2 and >>= 1 (right shift) instead of //= 2. Many developers find this version more intuitive when thinking about binary operations.
Practical Applications
Displaying Bit Flags
Network Subnet Masks
Byte Inspection
The # flag in the format specifier adds the 0b prefix, and 010 pads to 10 characters total (including the 0b).
Comparison with Other Bases
Python's format specifiers handle all common bases:
Common Pitfalls
The most common mistake is forgetting that bin() includes the 0b prefix. Comparing bin(45) directly to '101101' returns False because the actual value is '0b101101'. Use format(n, 'b') when you need bare digits.
Expecting bin(-5) to return a two's complement pattern is another frequent error. Python integers are arbitrary precision, so there is no fixed-width machine representation. Mask with & 0xFF or similar to get two's complement at a specific width.
Treating the binary string as a number instead of text leads to bugs. f'{13:08b}' returns the string '00001101', not the integer 1101. If you need to do arithmetic, convert back with int('00001101', 2).
Writing manual conversion functions when the built-in tools already handle the job adds unnecessary complexity and potential bugs. The format() function and f-strings are well-tested and cover all standard use cases. Reserve manual implementations for educational contexts.
Forgetting to specify a width when displaying byte-level data makes output hard to read. format(5, 'b') returns '101', which is correct but ambiguous when you expect 8-bit alignment. Always use '08b' or similar when the bit width matters.
Summary
- Use
bin(n)for quick inspection with the0bprefix. - Use
format(n, 'b')orf'{n:b}'for clean binary digit strings without the prefix. - Add a width specifier like
'08b'for fixed-width output with leading zeros. - Mask negative values to a specific width (
value & 0xFF) for two's complement representation. - Convert binary strings back to integers with
int(binary_str, 2). - Prefer built-in formatting tools over manual conversion in production code.

