0

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...)

IamAlexAlright
  • 1,500
  • 1
  • 16
  • 29

2 Answers2

3

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!

tomasz
  • 12,574
  • 4
  • 43
  • 54
  • I looked at struct but I get a different value than what I am expecting (on the same machine). unpack("Q", array) gives 9096440085217280 (but the value should be 140734054361456 ) – IamAlexAlright Jul 02 '12 at 18:58
  • The value of '0x7fff33516970' does not look right: print bin(long('0x7fff33516970',16)) gives 0b11111111111111100110011010100010110100101110000. – Yevgen Yampolskiy Jul 02 '12 at 19:05
  • Well, true, `\x00\x00\x00\x00*Q \x00` is definitely not `0x7fff33516970`. @IamAlexAlright, how do you check the value of you number? Are you sure you're printing out `*value`, not `value` which would be just the address of your variable? – tomasz Jul 02 '12 at 19:12
1

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.

Qnan
  • 3,714
  • 18
  • 15
  • that's a good point; @IamAlexAlright, is your code the real code or just an example when you're trying to express what it should say? – tomasz Jul 02 '12 at 19:02
  • @tomasz: just a paraphrase of the code - I can pastebin the whole thing if people really need to see it (but I don't think it has any bearing on my question) – IamAlexAlright Jul 02 '12 at 19:03