2012-12-12 46 views
0

我寫了2個funcs工作良好,但我想更改一部分代碼以使其效率更高,使用循環和每個8個圖表的「跳轉」。 當我運行verify_checksum,我得到:for循環 - .split和int

AttributeError: 'int' object has no attribute 'split' 

但是當我用線條與言論運行#它正常工作。 任何想法如何修改它而不改變代碼的其他部分? (有更多的funcs與這些工作,並導致一團糟)。

我的代碼:

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 

回答

1

在註釋掉的行中,您傳遞了兩個字符串作爲參數。

在循環中,你傳遞一個字符串和一個int作爲參數。

錯誤在byte2.split()上,因爲它是一個int。通過數據報的一部分,而不是數字位置,你會沒事的。

2

你有for循環是這樣的:

for i in (16,88,8): 
    res=xor_bytes(res, i) 

然後嘗試撥打.spliti(這是一個整數)在xor_bytes功能:

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]) 
2

你的循環不看什麼註釋行等。

for i in range(16,88,8): 
    res=xor_bytes(res, datagram[i:i + 8]) 
+0

你的修復比我的更好一點。 +1。 – mgilson

+0

你對! 我從舊文件複製..我做了什麼 – user1816377