Convert an int to a binary string in Python
Codemia Knowledge Hub ·
Use bin(n) to convert an integer to a binary string in Python; it returns a string like '0b101101'. For output without the 0b prefix, use format(n, 'b') or the f-string f'{n:b}'. For fixed width with leading zeros, add a width specifier such as f'{n:08b}'.
bin(), format() and f-strings
All three built-ins produce the binary representation; they differ only in formatting.
| 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.
Remember that bin() includes the prefix: bin(45) == '101101' is False because the value is '0b101101'. Use format(n, 'b') when you need bare digits.
Fixed width with leading zeros
Byte values, bit masks and protocol fields usually need a fixed number of digits:
08b means pad with zeros to 8 characters and format as binary. It is clearer than prepending zeros with zfill():
Without a width, format(5, 'b') returns '101', which is correct but hard to read when you expect 8-bit alignment. Use '08b' or similar whenever bit width matters.
Negative numbers and two's complement
Because Python integers are arbitrary precision, there is no fixed bit width, and bin(-5) returns the sign plus the magnitude rather than a two's complement pattern:
Getting a two's complement string
To get a fixed-width two's complement representation (how hardware stores negative integers), mask the value to the desired width:
The bitwise AND with a mask (0xFF for 8 bits, 0xFFFF for 16 bits) forces the two's complement representation at that width.
Converting two's complement back to signed
Converting a binary string back to an int
int() parses binary strings:
The second argument is the base: 2 for binary, 8 for octal, 16 for hexadecimal. The result of f'{13:08b}' is the string '00001101', not a number, so convert it back with int('00001101', 2) before doing arithmetic.
Manual conversion
The built-ins are well-tested and cover standard use cases, so keep manual implementations for learning how the conversion works.
Repeated division
Repeated division builds the string from least significant to most significant bit:
Each iteration takes the remainder of division by 2 (the current least significant bit), then integer-divides by 2 to shift right. The bits are collected in reverse and reversed at the end.
Bit shifts and masks
This is logically identical to the division method, using & 1 instead of % 2 and >>= 1 instead of //= 2. Many developers find it more intuitive when thinking in binary.
Practical uses
Displaying bit flags
Network subnet masks
Inspecting bytes
The # flag adds the 0b prefix, and 010 pads to 10 characters total, including the 0b.
Binary, octal and hex format specifiers
Related reading
- Convert integer to string in Python
- Convert Iterator to List
- Convert JSON string to dict using Python
- Convert key1,val1,key2,val2 to a dict?
- Convert list of dictionaries to a pandas DataFrame
- Convert list to tuple in Python
- Convert NumPy array to Python list
- Convert Pandas column containing NaNs to dtype int
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.