C++读取保存为二进制的 numpy 数组
首先需要确定C++和Python中变量对应的精度类型,
https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types
常用的,
C++int
对应Pythonnp.intc
C++float
对应Pythonnp.single
C++double
对应Pythonnp.double
numpy数组保存为二进制文件
import numpy as np a = np.array([[1.888,2.8888,3.88888],[4.666,5.6666,6.66666]]) a = a.astype(np.double) a.astype('double').tofile("varr.data")
C++读取二进制文件
#include <iostream> #include <fstream> using namespace std; int main() { double fnum[2][3] = {0}; ifstream in("varr.data", ios::in | ios::binary); in.read((char *) &fnum, sizeof fnum); // see how many bytes have been read cout << in.gcount() << " bytes read\n"; for(int j=0; j<3; j++) // show values read from file cout << fnum[0][j] << " "; in.close(); return 0; }
如果数据类型对应关系错了,例如把a.astype(‘double‘).tofile("varr.data")
改成a.astype(‘float
).tofile("varr.data")`,C++中读取的数组将不再是原来的数组。需要特别注意。
相关推荐
文山羊 2020-11-07
susmote 2020-11-07
拉斯厄尔高福 2020-11-04
xceman 2020-10-23
hellojunz 2020-10-23
caojhuangy 2020-10-12
xinyupan 2020-09-28
lousir 2020-09-27
一个逗逗 2020-09-22
Maryhuan 2020-09-20
rkhstar 2020-09-09
DreamSnow 2020-09-09
aehousmantao 2020-09-03
tkernel 2020-09-03
abfdada 2020-08-26
svap 2020-08-25
二十不悔三十而立 2020-08-19
FlightForever 2020-08-17
joyjoy0 2020-08-13