我有 C 代码片段(从 IDA 反编译)要翻译为 Python:
# v29 = 0;
# v30 = -1342924972;
# while ( v29 < v62 ) // v62 is length of string to be decoded
# {
# v31 = (int *)v60;
# v32 = __ROL4__(v30, 3);
# v33 = *((_BYTE *)v31 + v29) - v29 - v32;
# v34 = (int *)v60;
# *((_BYTE *)v34 + v29) = v33;
# v35 = __ROR4__(v33, 11);
# v36 = __ROL4__(v30, 5);
# v30 = v30 + (v29++ ^ v36 ^ v35) - 1204489519;
# }
def decode_msg(dstr, str_len):
bstr = list(dstr)
v29 = 0
v32 = 0
v33=0
v35=0
v30 = -1342924972
while(v29 < str_len):
v32 = ((v30 & 0xffffffff) << 3) & 0xffffffff
v33 = ((hex(ord(bstr[v29])) & 0xff) - v32) & 0xff
bstr[v29] = v33 & 0xff
v35 = ((v33 & 0xffffffff) >> 11) & 0xffffffff
v36 = ((v30 & 0xffffffff) << 5) & 0xffffffff
v29 = v29 + 1
v30 = (v30 & 0xffffffff) + (v29 ^ v36 ^ v35) - 1204489519
return ''.join(bstr)
C 代码在注释中。 C代码解码一个字节数组,v60就是数组。我有错误:
v33 = ((hex(ord(bstr[v29])) & 0xff) - v32) & 0xff
TypeError: unsupported operand type(s) for &: 'str' and 'int'
我完全是Python菜鸟。我认为 hex()
将 dstr
中的每个项目转换为数字。那么为什么它仍然是str
?
最佳答案
如上所述,hex
返回一个字符串,显然不支持&
这样的按位运算具有数字类型:
>>> type(hex(3))
<class 'str'>
>>> hex(3) & 0xf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'int'
ord
函数已经返回一个 int,所以你可以删除 hex
功能总计:
>>> ord('c') & 0xff
99
关于python - 将 C 代码转换为 Python 时语法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40892551/