Convert binary to ASCII and vice versa

前端 未结 8 1307
余生分开走
余生分开走 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:24

    if you don'y want to import any files you can use this:

    with open("Test1.txt", "r") as File1:
    St = (' '.join(format(ord(x), 'b') for x in File1.read()))
    StrList = St.split(" ")
    

    to convert a text file to binary.

    and you can use this to convert it back to string:

    StrOrgList = StrOrgMsg.split(" ")
    
    
    for StrValue in StrOrgList:
        if(StrValue != ""):
            StrMsg += chr(int(str(StrValue),2))
    print(StrMsg)
    

    hope that is helpful, i've used this with some custom encryption to send over TCP.

提交回复
热议问题