I am in need of a way to get the binary representation of a string in python. e.g.
st = "hello world"
toBinary(st)
Is there a module of some neat way of doing this?
Answers
You can convert a string to its binary representation in Python using built-in functions like bin()
and ord()
. Here's a simple way to achieve this:
Example of converting a string to its binary representation:
def toBinary(string):
return ' '.join(format(ord(char), '08b') for char in string)
# Example usage:
st = "hello world"
binary_representation = toBinary(st)
print(binary_representation)
How it works:
ord(char)
converts each character in the string to its ASCII value.format(..., '08b')
converts the ASCII value to its binary equivalent, ensuring that the binary string is 8 bits long (padded with leading zeros if necessary).' '.join(...)
combines the binary representations of each character into a single string, with spaces separating the binary numbers for readability.
Output for "hello world"
:
01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100
This approach is neat, avoids external modules, and works for any string.