【问题标题】:Why do I get the error为什么我会收到错误消息
【发布时间】:2015-01-25 16:40:21
【问题描述】:
# 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,但我没有成功。你有什么建议?

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多