2015-02-11 103 views
0

我有一個算法,我想用python編寫並分析它。我認爲我寫得很好,但是我的輸出與給定輸出應該不匹配。給定算法爲爲什麼我應該失敗這個簡單的Python算法?

;在python

Input{inStr: a binary string of bytes} 
Output{outHash: 32-bit hashcode for the inStr in a series of hex values} 
Mask: 0x3FFFFFFF 
outHash: 0 
for byte in input 
intermediate_value = ((byte XOR 0xCC) Left Shift 24) OR 
((byte XOR 0x33) Left Shift 16) OR 
((byte XOR 0xAA) Left Shift 8) OR 
(byte XOR 0x55) 
outHash =(outHash AND Mask) + (intermediate_value AND Mask) 
return outHash 

我的算法版本;

Input = "Hello world!" 
Mask = 0x3FFFFFFF 
outHash = 0 

for byte in Input: 
    intermediate_value = ((ord(byte)^0xCC) << 24) or ((ord(byte)^0x33) << 16) or ((ord(byte)^0xAA) << 8) or (ord(byte)^0x55) 
outHash =(outHash & Mask) + (intermediate_value & Mask) 

print outHash 

# use %x to print result in hex 
print '%x'%outHash 

對於輸入「你好!世界」,我應該看到的0x50b027cf輸出,但我的輸出是太不一樣了,它看起來像;

1291845632 
4d000000 
+1

您在每次迭代時覆蓋您的_intermediate_value_,基本上使用它的值爲最後_byte_唯一 – volcano 2015-02-11 07:32:23

回答

3

OR必須位OR運算符(|)。

+0

謝謝,這可能只是問題 – user124627 2015-02-11 07:14:05

+0

@ user124627,您錯了。 _1或2_給出1,_0或2_給出2. _1 | 2_給出3 – volcano 2015-02-11 07:18:22

+0

實際上,因爲所有的值都落入不同的字節偏移量,所以加法也會起作用 - 至少,現在寫入的方式 – volcano 2015-02-11 07:54:32

相關問題