简体   繁体   中英

How to unpack numbers in cpp if they are pack at python using struct.pack(fmt, v1, v2, …)

In python, I encoded numbers using struct

struct.pack("<2q", 456, 123)

It returns

'\xc8\x01\x00\x00\x00\x00\x00\x00{\x00\x00\x00\x00\x00\x00\x00'

In cpp, how could I decode such string into a tuple of integers?

It should be fairly simple to unpack that string, you can just copy the bytes out into the appropriate sized integer:

#include <iostream>
#include <string>
#include <cstring>

int main()
{
  std::string input = std::string("\xc8\x01\x00\x00\x00\x00\x00\x00{\x00\x00\x00\x00\x00\x00\x00", 16);
  for ( size_t i = 0; i < input.size() / 8; i++ )
  {
      int64_t value;
      memcpy(&value, &input[i*8], 8);
      std::cout << value << "\n";
  }
}

q is long long so 64 bit signed integers. From https://docs.python.org/3/library/struct.html :

Format  C Type      Python type     Standard size
q      long long    integer         8

You could read this buffer and copy into an array of 2 long long (64 bit using stdint.h define)

#include <iostream>
#include <strings.h>
#include <stdint.h>

int main()
{
 // you're supposed to get that when reading the buffer from a file for instance:
 const unsigned char buffer[] = {0xc8,0x01,0x00,0x00,0x00,0x00,0x00,0x00,'{',0x00,0x00,0x00,0x00,0x00,0x00,0x00};
 int64_t array[2];
 memcpy(array,buffer,sizeof(array));
 std::cout << array[0] << "," << array[1] << '\n';
}

prints:

456,123

I didn't handle endianness here. Just assumed they were the same. But if you want that, just swap the bytes using the size of the type and you're good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM