Convert String to Binary - Python
Converting a string to binary means changing each character in the string to its binary form using its character code (like ASCII).
For Example:
String: "Hi"
Step 1: Convert characters to ASCII
H → 72
i → 105Step 2: Convert ASCII to Binary
72 → 01001000
105 → 01101001Final Binary: 01001000 01101001
Let's explore different ways to convert string to binary.
Using join() + ord() + format()
This method converts a string to binary by:
- ord(char) gets ASCII number of each character
- format(num, '08b') converts that number to 8-bit binary
- join() joins all binary pieces into one string
txt = "Gfg"
b = ''.join(format(ord(char), '08b') for char in txt)
print(b)
Output
010001110110011001100111
Explanation: converts each character in txt to its 8-bit binary form using ord() and format() then joins them into one binary string using join().
Using join() + bytearray() + format()
This method converts a string to binary by:
- bytearray() convert whole string into bytes (numbers)
- format() convert each byte to 8-bit binary
- join() combine all binary values into one string
txt = "Gfg"
b = ''.join(format(b, '08b') for b in bytearray(txt, 'utf-8'))
print(b)
Output
010001110110011001100111
Explanation: converts each character in txt to its 8-bit binary form using bytearray() and format() then joins them into one binary string.
Using join() + bin() + zfill()
This method converts a string to binary by:
- ord() get each character’s ASCII value
- bin() convert it to binary (removes the '0b' prefix)
- zfill(8) make sure each binary number is 8 bits
- join() combine all binary values into one string
txt = "Gfg"
b = ''.join(bin(ord(c))[2:].zfill(8) for c in txt)
print(b)
Output
010001110110011001100111
Explanation: converts each character of txt to its 8-bit binary form using ord(), bin() and zfill(8) then joins them into one binary string.
Using binascii module
binascii module can convert a string to binary by first encoding it to hexadecimal using hexlify() then converting that hex value to binary using bin().
import binascii
txt = "Gfg"
h = binascii.hexlify(txt.encode())
b = bin(int(h, 16))[2:].zfill(8 * len(txt))
print(b)
Output
010001110110011001100111
Explanation:
- text.encode() converts string to bytes and binascii.hexlify() turns those bytes into a hexadecimal string
- bin(int(..., 16))[2:] converts the hex string to binary, removing the '0b' prefix
- zfill() ensures the binary string is properly padded to 8 bits per character
Related Articles: