Friday, December 30, 2016

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)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.