Skip to content

How to Convert a String to Binary in Python

Learn how to convert strings to binary in Python, handle Unicode and emojis with UTF-8 encoding, and build reusable functions for reliable text-to-binary conversion.

Converting strings to binary representation is a fundamental skill for developers working with cryptography, data compression, network protocols, or low-level data manipulation. Understanding how text maps to binary helps you work confidently with any system that operates at the byte level.

In this guide, you will learn how to convert strings to their binary representation and back, handle Unicode characters including emojis, and build reusable functions for production code.

Understanding the Basics

Computers store text as numeric codes (ASCII or Unicode), which are ultimately represented as binary bits. Converting a string to binary means transforming each character into its binary equivalent.

For example, the character 'A' has a Unicode code point of 65, which is 01000001 in binary.

Converting a String to Binary Using format()

The most straightforward approach iterates over each character, retrieves its Unicode code point with ord(), and formats it as an 8-bit binary string:

text = "ABC"

binary_list = [format(ord(c), '08b') for c in text]

binary_str = " ".join(binary_list)
print(binary_str)

Output:

01000001 01000010 01000011

Understanding the Format Specifier

The '08b' format specifier consists of three parts:

Component Meaning
0 Pad with leading zeros
8 Total width of 8 characters
b Binary format

Converting Binary Back to a String

Reversing the process requires splitting the binary string into individual byte representations, parsing each one as a base-2 integer, and converting it back to a character:

binary_input = "01000001 01000010 01000011"

text = "".join(chr(int(b, 2)) for b in binary_input.split())

print(text)

Output:

ABC

Handling Unicode and Emojis with UTF-8 Encoding

The ord() approach works for basic characters, but multi-byte Unicode characters like emojis do not fit in 8 bits. For full Unicode support, encode the string to bytes first:

text = "Hi 🐍"

binary_str = " ".join(format(byte, '08b') for byte in text.encode('utf-8'))

print(binary_str)

Output:

01001000 01101001 00100000 11110000 10011111 10010000 10001101

Decoding UTF-8 Binary Back to a String

binary_input = "01001000 01101001 00100000 11110000 10011111 10010000 10001101"

byte_values = bytes(int(b, 2) for b in binary_input.split())
text = byte_values.decode('utf-8')

print(text)

Output:

Hi 🐍

Why UTF-8 Encoding Matters

The simple ord() approach and the UTF-8 byte approach produce different results for non-ASCII characters:

text = "é"  # e with acute accent

print(f"Code point: {ord(text)}")
print(f"ord() binary: {format(ord(text), '08b')}")

utf8_bytes = text.encode('utf-8')
print(f"UTF-8 bytes: {list(utf8_bytes)}")
print(f"UTF-8 binary: {' '.join(format(b, '08b') for b in utf8_bytes)}")

Output:

Code point: 233
ord() binary: 11101001
UTF-8 bytes: [195, 169]
UTF-8 binary: 11000011 10101001

The ord() approach gives you the raw code point in binary, while UTF-8 encoding gives you the actual byte representation used for storage and transmission. For most real-world applications, the UTF-8 approach is what you need.

Reusable Conversion Functions

For production code, wrap these operations in reusable functions with proper error handling:

def string_to_binary(text: str, encoding: str = 'utf-8') -> str:
    """Convert a string to a space-separated binary representation."""
    return ' '.join(format(byte, '08b') for byte in text.encode(encoding))

def binary_to_string(binary_str: str, encoding: str = 'utf-8') -> str:
    """Convert a space-separated binary string back to text."""
    byte_values = bytes(int(b, 2) for b in binary_str.split())
    return byte_values.decode(encoding)

original = "Hello, 世界! 🌍"
binary = string_to_binary(original)
restored = binary_to_string(binary)

print(f"Original:  {original}")
print(f"Binary:    {binary[:56]}...")
print(f"Restored:  {restored}")
print(f"Match:     {original == restored}")

Output:

Original:  Hello, 世界! 🌍
Binary:    01001000 01100101 01101100 01101100 01101111 00101100 00...
Restored:  Hello, 世界! 🌍
Match:     True

The round-trip test confirms that the original string is perfectly preserved through the conversion and back.

Quick Reference

Goal Code
String to binary (ASCII) ' '.join(format(ord(c), '08b') for c in s)
String to binary (UTF-8) ' '.join(format(b, '08b') for b in s.encode())
Binary to string (ASCII) ''.join(chr(int(x, 2)) for x in binary.split())
Binary to string (UTF-8) bytes(int(x, 2) for x in binary.split()).decode()

Conclusion

Converting strings to binary in Python is straightforward once you understand the relationship between characters, their numeric code points, and binary encoding. For ASCII-only text, the ord() and chr() functions with format(n, '08b') work perfectly. For modern applications that handle international text, accented characters, or emojis, always use UTF-8 byte encoding to ensure complete Unicode support and compatibility with how text is actually stored and transmitted in real systems.

Navigation