Translating C++ to python - memcpy uchar into int64
Вопрос
Alright, I'm copying some code (C++) that needs to run on my server (Python), everything was going well until the bit below.
In a nutshell here is what I have in the C++ program:
int main() {
...
...
int64 value = 0;
bool blah = function1(&value);
...
}
bool function1(int64* value)
{
...
uchar pb[8];
pb = '\x00\x00\x00\x00*Q \x00';
memcpy(value,pb,8);
//now value has the value '0x7fff33516970'
}
So yeah, it creates some char array and then copies the value into an int64.
Now my question is: how do I do that in Python? I mean, I have the bytestring that is equivalent to pb but I have no idea where to go from there (especially since there are all those zeroes...)
Решение
Take a look at struct
module, especially at struct.unpack
. You can do:
value, = unpack("q", string)
"q" means 64-bit signed integer and string is simply a raw byte representation of the number. And remember, watch out the endianness!
Другие советы
Single quotes are used for characters, not strings in C++. Should be "\x00\x00\x00\x00*Q \x00"
. Besides, the code makes little sense in that memory is allocated for pb
and then it's overwritten with a constant string.