我有一個算法,我想用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
您在每次迭代時覆蓋您的_intermediate_value_,基本上使用它的值爲最後_byte_唯一 – volcano 2015-02-11 07:32:23