C++读取numpy数据二进制文件

C++读取numpy数据二进制文件


C++与Python中变量对应的精度类型:
https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types

C++读取numpy数据二进制文件_第1张图片

(1)将numpy数组保存为二进制文件

def save_bin(data, bin_file, dtype="double"):
    """
    C++int对应Python np.intc
    C++float对应Python np.single
    C++double对应Python np.double
    :param data:
    :param bin_file:
    :param dtype:
    :return:
    """
    data = data.astype(np.double)
    data.astype(dtype).tofile(bin_file)

(2)用numpy读取二进制文件


def load_bin(bin_file, shape=None, dtype="double"):
    """
    :param bin_file:
    :param dtype:
    :return:
    """
    data = np.fromfile(bin_file, dtype=dtype)
    if shape:
        data = np.reshape(data, shape)
    return data

if __name__ == "__main__":
    bin_file = "data.bin"
    shape = (2, 5)
    data1 = np.arange(10, 20).reshape(shape)
    save_bin(data1, bin_file)
    data2 = load_bin(bin_file, shape)
    print(data1)
    print(data2)

(3)用C++读取二进制文件

#include 
#include 
using namespace std;

int main()
{
  int row=2;
  int col=5;
  double fnum[row][col] = {0};
  ifstream in("bin/data.bin", ios::in | ios::binary);
  in.read((char *) &fnum, sizeof fnum);
  cout << in.gcount() << " bytes read\n";
  // show values read from file
  for(int i=0; i

输出结果:

你可能感兴趣的:(C,/,C++,Python)