将C代码转换为Python时语法无效

时间:2016-11-30 15:48:43

标签: python c

我有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 noob。我认为hex()会将dstr中的每个项目转换为数字。那为什么它仍然是str

2 个答案:

答案 0 :(得分:2)

如前所述,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

答案 1 :(得分:2)

ord已经是一个int,你不需要hex,它返回一个字符串。

我可能错了,但这一行可能会给你带来麻烦

bstr[v29] = v33 & 0xff

您需要再次将其强制转换为字符串:

bstr[v29] = chr(v33 & 0xff)