简体   繁体   English

如何将二进制解码为ASCII?

[英]How to decode binary to ASCII?

I'm a python programmer and I have a problem I can transform my input in to binary:我是 python 程序员,我有一个问题,我可以将输入转换为二进制:

bnr = open("binary.bin", "w")
tobinary = input("Enter whatever you want : ")
limit = 100
d = tobinary.encode()
if limit >= len(tobinary):
    for i in d:
        bnr.write(bin(i)[2:])
    bnr.close()
bi = open("binary.bin", "r")
read = bi.read()
bi.close()
print(read)

But I can't do inverse please help.但我不能做逆向请帮忙。

Actually, with the approach you are doing you will not be able to do it as all the binary data gets joined up.实际上,使用您正在执行的方法,您将无法执行此操作,因为所有二进制数据都已连接在一起。 Instead you need to put in a separator between all these binaries and use chr() and int() to recreate the data.相反,您需要在所有这些二进制文件之间放置一个分隔符,并使用 chr() 和 int() 重新创建数据。

bnr = open("binary.bin", "w")
tobinary = input("Enter whatever you want : ")
limit = 100
d = tobinary.encode()
if limit >= len(tobinary):
    for i in d:
        bnr.write(bin(i)[2:]+' ')
    bnr.close()
bi = open("binary.bin", "r")
read = bi.read()
bi.close();
print(''.join([chr(int(x,2)) for x in read.split(' ')[:-1]]))

My final Code我的最终代码

#ASCII to Binary function
def ToBinary():
    bnr = open("binary.bin", "w")
    tobinary = input("Enter whatever you want : ")
    limit = 10000
    d = tobinary.encode()
    if limit >= len(tobinary):
        for i in d:
            bnr.write(bin(i)[2:]+' ')
        bnr.close()
    bi = open("binary.bin", "r")
    read = bi.read()
    bi.close();
    print(read)
#Binary to ASCII function
def ToASCII():
    aci = open("text.txt", "w")
    aci.write(''.join([chr(int(x,2)) for x in read.split(' ')[:-1]]))
    aci.close()
    asi = open("text.txt", "r")
    read1 = asi.read()
    asi.close()
    print(read1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM