Sling Academy
Home/Python/Python: 3 Ways to Convert a String to Binary Codes

Python: 3 Ways to Convert a String to Binary Codes

Last updated: June 01, 2023

Binary codes (binary, binary numbers, or binary literals) are a way of representing information using only two symbols: 0 and 1. They are like a secret language that computers are able to understand. By combining these symbols in different patterns, we can represent numbers, letters, and other data.

This concise, example-based article will walk you through 3 different approaches to turning a given string into binary in Python.

Using the ord() function and string formatting

What we’ll do are:

  1. Loop through each character in the string.
  2. Convert each character to its corresponding Unicode code using the ord() function.
  3. Convert the Unicode code to binary using the format() function with a format specifier.
  4. Concatenate the binary codes to form the final binary string.

Code example:

input = "Sling Academy"
binary_codes = ' '.join(format(ord(c), 'b') for c in input)
print(binary_codes)

Output:

1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001

Using the bytearray() function

Here’re the steps:

  1. Convert the string to a bytearray object, which represents the string as a sequence of bytes.
  2. Iterate over each byte in the bytearray.
  3. Convert each byte to binary using the format() function with a format specifier.
  4. Concatenate the binary codes to form the final binary string.

Code example:

my_string = "Sling Academy"
byte_array = bytearray(my_string, encoding='utf-8')
binary_codes = ' '.join(bin(b)[2:] for b in byte_array)
print(binary_codes)

Output:

1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001

Using the bin() and ord() functions

This technique can be explained as follows:

  1. Iterate over each character in the string.
  2. Convert each character to its corresponding Unicode code using the ord() function.
  3. Use the bin() function to convert the Unicode code to binary.
  4. Remove the leading 0b prefix from each binary code.
  5. Concatenate the binary codes to form the final binary string.

Thanks to Python’s concise syntax, our code is very succinct:

text = "Sling Academy"
binary_string = ' '.join(bin(ord(char))[2:] for char in text)
print(binary_string)

Output:

1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001

Conclusion

You’ve learned some methods to transform a given string into binary in Python. All of them are neat and delicate. Choose the one you like to go with. Happy coding & have a nice day!

Next Article: 2 ways to get the size of a string in Python (in bytes)

Previous Article: Python: How to Convert a String to Character Codes

Series: Working with Strings in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots