Convert binary to ASCII and vice versa

前端 未结 8 1143
余生分开走
余生分开走 2020-11-22 03:22

Using this code to take a string and convert it to binary:

bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in \'hello\'), 0))

this outputs:<

8条回答
  •  你的背包
    2020-11-22 04:26

    Built-in only python

    Here is a pure python method for simple strings, left here for posterity.

    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])
    
    s = 'Hello, World!'
    b = string2bits(s)
    s2 = bits2string(b)
    
    print 'String:'
    print s
    
    print '\nList of Bits:'
    for x in b:
        print x
    
    print '\nString:'
    print s2
    

    String:
    Hello, World!
    
    List of Bits:
    01001000
    01100101
    01101100
    01101100
    01101111
    00101100
    00100000
    01010111
    01101111
    01110010
    01101100
    01100100
    00100001
    
    String:
    Hello, World!
    

提交回复
热议问题