[英]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. 好的,我正在复制一些需要在服务器(Python)上运行的代码(C ++),一切进行得很好,直到下面为止。
In a nutshell here is what I have in the C++ program: 简而言之,这就是我在C ++程序中所拥有的:
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. 是的,它创建了一些char数组,然后将值复制到int64中。
Now my question is: how do I do that in Python? 现在我的问题是:如何在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...)
我的意思是,我有一个等效于pb的字节串,但我不知道从那里开始(特别是因为所有这些零...)
Take a look at struct
module, especially at struct.unpack
. 看一下
struct
模块,尤其是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. “ q”表示64位有符号整数,字符串只是数字的原始字节表示形式。 And remember, watch out the endianness!
记住,要注意字节序!
Single quotes are used for characters, not strings in C++. 单引号用于字符,而不是C ++中的字符串。 Should be
"\\x00\\x00\\x00\\x00*Q \\x00"
. 应该是
"\\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. 此外,该代码没有意义,因为已为
pb
分配了内存,然后用常量字符串覆盖了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.