JACK M JACK M - 5 days ago 5
C Question

syntax invalid while translating C code to Python

I have C snippet(decompiled from IDA) to be translated to 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 code is in comments. The C code decodes a byte array, v60 is the array. I have error:

v33 = ((hex(ord(bstr[v29])) & 0xff) - v32) & 0xff
TypeError: unsupported operand type(s) for &: 'str' and 'int'


I am totally Python noob. I think
hex()
converts each item in
dstr
to a number. So why is it still
str
?

Answer

As mentioned, hex returns a string, which obviously does not support bitwise operations like & with a numeric type:

>>> 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'

The ord function already returns an int, so you can just remove the hex function altogether:

>>> ord('c') & 0xff
99
Comments