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

标签 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菜鸟。我认为 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/

相关文章:

python - 我游戏中的 "lives"不会出现?游戏

Python 单元测试模拟 : Is it possible to mock the value of a method's default arguments at test time?

c - Sscanf 和 fgets 在 C 中的正确用法 - 注意 : edited

c - 阅读双倍时的 scanf 问题

c - 在 switch 语句中声明和初始化的变量

c++ - c中的非可移植符号整数

python - 使用 Scrapy 和 Python 2.7 递归抓取 Craigslist

python - 分离 JSON 中的唯一/重复数据

python - 如何获取类变量和类型提示?

c - 每次输入一个数字时,如何检查由连续用户输入提供的二进制数是否可以被 5 整除?