为什么我会收到错误

时间:2014-11-27 06:48:46

标签: python python-2.7 python-3.x wxpython subprocess

# Read the original Bitmap file, the goal is to encode the message in the original Bitmap file and get as an output the encoded Bitmap file
infile=open("C:\Users\Livio\Desktop\IMO2015.bmp","rb")
header=infile.read(54)
body=infile.read()
message=open("C:\Users\Livio\Desktop\Honourable Mention - IMO 2014.pdf","rb")
messagecontent=message.read()
outfile=open("C:\Users\Livio\Desktop\Output.bmp","wb")
outfile.write(header) #Below is the technique that I used for encoding the message
def base10tobase2(number):
    little_endian_digits_list=[]
    power=0
    while number>0:
            digit=number%(2**(power+1))
            number=number-digit
            little_endian_digits_list.append(digit/(2**power))
            power=power+1
    while len(little_endian_digits_list)<8:
            little_endian_digits_list.append(0)
    return little_endian_digits_list
y=54
for x in messagecontent:
    base2list=base10tobase2(ord(x))
    for z in base2list:
            if ord(body[y])==255:
                    z=z*(-1)
            outfile.write(chr(ord(body[y])+z)) 
            y=y+1
outfile.write(body[54:len(body)])
# Below I want to use the encoded Bitmap and the original Bitmap to obtain the message
INFILE=open("C:\Users\Livio\Desktop\IMO2015.bmp","rb")
BODY=INFILE.read()
OUTFILE=open("C:\Users\Livio\Desktop\Output.bmp","rb")
Body=OUTFILE.read()
MESSAGE=open("C:\Users\Livio\Desktop\mess.docx","wb")
# Below is my approach how to obtain the message
for i in range(0, len(messagecontent)*8):
    list=[]
    t=0
    for w in Body[54+i*8:54+(i+1)*8]:
            list.append(abs(ord(w)-ord(BODY[54+i*8+t])))
            t=t+1
    decimalnumber=sum(list[j]*(2**j) for j in range(0, 8))
    MESSAGE.write(chr(decimalnumber)) # When does it surpass 255 and why?
MESSAGE.write(Body[54:54+len(messagecontent)*8])

Traceback (most recent call last):
  File "C:\Users\Livio\Desktop\pro.py", line 42, in <module>
    MESSAGE.write(chr(decimal))
ValueError: chr() arg not in range(256)

如何解决此问题?到目前为止,我已经尝试过看到它超过255,但我还没有成功。你有什么建议?

另外,如果有任何方法可以更简单地获取消息,请提供其他想法。也许在几行代码之前,这种努力是不必要的。

1 个答案:

答案 0 :(得分:0)

检查何时超过255的最简单方法是将print(decimalnumber)放在MESSAGE.write(chr(decimalnumber))行之前。

出于一般设计考虑,我强烈建议不要使用幻数(在代码的上下文中是8,或2还是255?给出常量名称:例如ASCII_RANGE = 255

我还建议将代码分成一系列较小的步骤作为函数,并分别运行和测试每个函数。查看python的单元测试套件。

如果它对你正在做的事情有用,请查看内置的unistr()