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

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


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

(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 <iostream>
#include <fstream>
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<row; i++){
      for(int j=0;j<col;j++){
            cout << fnum[i][j] << ",";
      }
       std::cout<<endl;
  }
  in.close();
  return 0;
}

输出结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI吃大瓜

尊重原创,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值