Convert binary to ASCII and vice versa

前端 未结 8 1156
余生分开走
余生分开走 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!
    
    0 讨论(0)
  • 2020-11-22 04:27

    This is my way to solve your task:

    str = "0b110100001100101011011000110110001101111"
    str = "0" + str[2:]
    message = ""
    while str != "":
        i = chr(int(str[:8], 2))
        message = message + i
        str = str[8:]
    print message
    
    0 讨论(0)
提交回复
热议问题