Convert binary to ASCII and vice versa

前端 未结 8 1163
余生分开走
余生分开走 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:06

    This is a spruced up version of J.F. Sebastian's. Thanks for the snippets though J.F. Sebastian.

    import binascii, sys
    def goodbye():
        sys.exit("\n"+"*"*43+"\n\nGood Bye! Come use again!\n\n"+"*"*43+"")
    while __name__=='__main__':
        print "[A]scii to Binary, [B]inary to Ascii, or [E]xit:"
        var1=raw_input('>>> ')
        if var1=='a':
            string=raw_input('String to convert:\n>>> ')
            convert=bin(int(binascii.hexlify(string), 16))
            i=2
            truebin=[]
            while i!=len(convert):
                truebin.append(convert[i])
                i=i+1
            convert=''.join(truebin)
            print '\n'+'*'*84+'\n\n'+convert+'\n\n'+'*'*84+'\n'
        if var1=='b':
            binary=raw_input('Binary to convert:\n>>> ')
            n = int(binary, 2)
            done=binascii.unhexlify('%x' % n)
            print '\n'+'*'*84+'\n\n'+done+'\n\n'+'*'*84+'\n'
        if var1=='e':
            aus=raw_input('Are you sure? (y/n)\n>>> ')
            if aus=='y':
                goodbye()
    

提交回复
热议问题