A binary code translator is a tool or program that converts binary code (sequences of 0s and 1s) into human-readable text (ASCII or Unicode), and vice versa. You can easily create a binary translator in Python to convert text to binary and binary back to text.

Python Code for a Binary Translator

1. Text to Binary

This function will take any text and convert it to its binary (ASCII) equivalent.

python
def text_to_binary(text):
# Convert each character in the text to its binary ASCII value
binary_list = [format(ord(char), '08b') for char in text] # '08b' ensures 8-bit binary
return ' '.join(binary_list) # Join the binary values with spaces

# Example usage:
text = "Hello"
binary_code = text_to_binary(text)
print(f"Text: {text}\nBinary: {binary_code}")

  • Input: "Hello"
  • Output: 01001000 01100101 01101100 01101100 01101111

2. Binary to Text

This function will take binary input and convert it back into human-readable text.

python
def binary_to_text(binary_str):
# Split the binary string into chunks of 8 bits
binary_values = binary_str.split()
# Convert each binary string to its ASCII character
ascii_characters = [chr(int(b, 2)) for b in binary_values]
return ''.join(ascii_characters)

# Example usage:
binary_str = "01001000 01100101 01101100 01101100 01101111"
text = binary_to_text(binary_str)
print(f"Binary: {binary_str}\nText: {text}")

  • Input: "01001000 01100101 01101100 01101100 01101111"
  • Output: "Hello"

How It Works:

  • Text to Binary: The function converts each character in the string into its ASCII value using ord() and then formats it as an 8-bit binary string using format() with the '08b' option.
  • Binary to Text: The function splits the binary string into 8-bit chunks, converts each chunk back into a character using int(binary, 2) to interpret it as binary, and then uses chr() to get the character.

This is a simple binary translator that can be used for converting between text and binary code.

Sign In

Sign Up