2015-02-11 100 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

相关问题