Binary in Python
Intermediate · 5 min read · Updated 28 November 2026
In shortIn Python, bin(13) returns '0b1101', format(13, '08b') returns '00001101', and int('1101', 2) converts binary back to 13. For text, encode it to bytes first, then format each byte — ' '.join(f'{b:08b}' for b in 'Hi'.encode()) gives '01001000 01101001'.
Integer to binary
bin(13) # '0b1101'
format(13, 'b') # '1101'
f'{13:08b}' # '00001101' (8-bit, zero-padded)
f'{-5 & 0xFF:08b}' # '11111011' (8-bit two's complement)
Binary to integer
int('1101', 2) # 13
int('0b1101', 0) # 13 (base 0 reads the prefix)
0b1101 # 13 (binary literal)
Without built-ins (the doubling method):
def bin_to_int(s: str) -> int:
total = 0
for bit in s:
total = total * 2 + (bit == '1')
return total
Text to binary
def text_to_binary(text: str, sep: str = ' ') -> str:
return sep.join(f'{b:08b}' for b in text.encode('utf-8'))
text_to_binary('Hi') # '01001000 01101001'
text_to_binary('é') # '11000011 10101001'
Binary to text
def binary_to_text(bits: str) -> str:
bits = bits.replace(' ', '')
data = bytes(int(bits[i:i+8], 2) for i in range(0, len(bits), 8))
return data.decode('utf-8', errors='replace')
binary_to_text('01001000 01101001') # 'Hi'
Hex and octal
hex(255), oct(255) # ('0xff', '0o377')
bytes.fromhex('48656c6c6f').decode() # 'Hello'
'Hello'.encode().hex(' ') # '48 65 6c 6c 6f'
Bitwise operators
| Operator | Meaning | Example |
|---|---|---|
& |
AND | 0b1100 & 0b1010 == 0b1000 |
| |
OR | 0b1100 | 0b1010 == 0b1110 |
^ |
XOR | 0b1100 ^ 0b1010 == 0b0110 |
~ |
NOT | ~5 == -6 |
<< |
shift left (×2) | 5 << 1 == 10 |
>> |
shift right (÷2) | 10 >> 1 == 5 |
No Python handy? The text to binary and binary to decimal tools give the same answers in your browser.
Frequently asked questions
How do I remove the 0b prefix in Python?
Use format(n, 'b') or f'{n:b}' instead of bin(n). Add a width for padding, for example f'{n:08b}'.
How do I convert binary to decimal in Python without int()?
Loop over the digits, doubling the total and adding each bit — total = total * 2 + int(bit). It’s the same doubling method you can do by hand.
How do I get a list of bits from an integer?
Use [int(b) for b in f'{n:08b}'] for a fixed width, or [(n >> i) & 1 for i in range(7, -1, -1)] using bit shifts.
Next: Binary practice questions →