Convert String to Binary in Python
Code to convert string to binary and binary to string:
def string2bits(s=''):
return [bin(ord(x))[2:].zfill(8) for x in s]
def bits2string(b=None):
return ''.join([chr(int(x, 2)) for x in b])
si = input('\nenter text:\n')
b = string2bits(si)
so = bits2string(b)
print('\nyou entered\n' + si)
print('\nbinary is\n' + str(b))
print('\nstring is\n' + so)
return [bin(ord(x))[2:].zfill(8) for x in s]
def bits2string(b=None):
return ''.join([chr(int(x, 2)) for x in b])
si = input('\nenter text:\n')
b = string2bits(si)
so = bits2string(b)
print('\nyou entered\n' + si)
print('\nbinary is\n' + str(b))
print('\nstring is\n' + so)
This example converts text to its binary representation and back in Python by mapping each character to its 8 bit code with ord and bin, then reversing the process with int and chr.
It is a useful exercise for understanding character encoding and how text is stored as bytes underneath. For real binary handling, Python's bytes type and struct module are the practical tools.

Comments
Post a Comment