2012-06-28 254 views
0

能否請你幫我將這個C++代碼爲蟒蛇: 我想異或數據for循環C++ VS蟒蛇

C++:

void Encrypt(void data, Dword size) 
{ 
    if(size > 0) 
     for(DWORD i = size - 1; i > 0; i--) 
      ((LPBYTE)data)[i] ^= ((LPBYTE)data)[i - 1]; 
} 
+1

我假設你的意思是void *數據。 – Antimony

回答

0

要做到這一點在Python,你可能想使用bytearray類:

def encrypt(data): 
    n = len(data) 
    for i in range(n-1, 0, -1): 
     data[i] ^= data[i-1]  # for this to work, data has to be mutable 

f = open('somefile.bin', 'rb') 
buf = bytearray(f.read()) 
f.close() 

encrypt(buf) 

注意的評論,你不能傳遞一個字符串對象,因爲python中的字符串是不可變的。另一方面,bytearray不是。

+0

感謝喬納森,這似乎工作,但如何輸出數據大小加倍? – Roger

+0

它現在完美運作。欣賞你的時間並分享你的知識。你們都很棒! – Roger

1
def Encrypt(data, size): 
    for i in range(size-1, 0, -1): 
     data[i] = data[i]^data[i-1] 

雖然這ISN」非常pythonic。你可能會想刪除的明確的大小參數,只是使用LEN(數據)

+0

感謝銻,但出於某種原因,我得到這個錯誤「TypeError:^:'str'和'str'不受支持的操作數類型」任何想法? – Roger

+0

這是因爲你在字符串上運行它,因爲xor沒有意義。您可以通過說map(ord,s)將其轉換爲數字字節,其中s是您的字符串。 – Antimony