我写了2个运行良好的函数,但我想更改部分代码,使其更有效,使用for循环,每8个图表“跳转”一次。当我运行verify_checksum时,我得到:
AttributeError: 'int' object has no attribute 'split'但是,当我用#运行它的时候,它工作得很好。你知道如何在不改变代码其他部分的情况下修复它吗?(有更多的函数可以与这些函数一起工作,这会导致混乱)。
我的代码:
def xor_bytes(byte1, byte2):
byte1, byte2=byte1.split(), byte2.split()
xor=""
a=0
for i in byte1:
for j in i:
t=int(byte2[0][a])^int(j)
xor+="".join(str(t))
a+=1
return xor
def verify_checksum(datagram):
datagram=list(datagram)
org_checksum=datagram[48:56]
org_checksum="".join(org_checksum)
x=48
for i in datagram[48:56]:
datagram[x]='0'
x+=1
datagram="".join(datagram)
res=xor_bytes(datagram[0:8], datagram[8:16])
for i in (16,88,8):
res=xor_bytes(res, i)
#res=xor_bytes(res,datagram[16:24])
#res=xor_bytes(res,datagram[24:32])
#res=xor_bytes(res,datagram[32:40])
#res=xor_bytes(res,datagram[40:48])
#res=xor_bytes(res,datagram[48:56])
#res=xor_bytes(res,datagram[56:64])
#res=xor_bytes(res,datagram[64:72])
#res=xor_bytes(res,datagram[72:80])
#res=xor_bytes(res,datagram[80:88])
if res==org_checksum:
return True
else:
return False 输入:
verify_checksum("1111000000001111000011111111000001010101101010101010111001110011001000000110101101101001")输出:
True发布于 2012-12-13 00:57:24
在被注释掉的行中,您传递了两个字符串作为参数。
在循环中,您将传递一个字符串和一个int作为参数。
错误出现在byte2.split()上,因为它是一个int类型。传入数据报的一个部分,而不是一个数字位置,就没问题了。
发布于 2012-12-13 00:53:45
您有一个如下所示的for循环:
for i in (16,88,8):
res=xor_bytes(res, i)然后,尝试在xor_bytes函数中对i (一个整数)调用.split:
byte1, byte2=byte1.split(), byte2.split()(i作为byte2传入)。
我不是很确定您在这里想要实现什么,所以我不能帮助您解决这个问题,但这就是它发生的原因。
也许你想要这样的东西:
bytes_range = range(16,89,8) #make 89 the upper bound so that 88 is included in the range
for start,end in zip(bytes_range[:-1],bytes_range[1:]):
res = xor_bytes(res,datagram[start:end])发布于 2012-12-13 00:56:58
你的循环看起来并不像注释行那样。
for i in range(16,88,8):
res=xor_bytes(res, datagram[i:i + 8])https://stackoverflow.com/questions/13844592
复制相似问题