【发布时间】:2017-08-25 19:35:14
【问题描述】:
我正在 python 中创建一个名为 random_from_python_int.dat 的 5*7 整数矩阵二进制文件,然后我从 C 中读取这个二进制文件。不知何故我无法获得正确的数字 这是我生成这个矩阵的python代码:
import numpy as np
np.random.seed(10)
filename = "random_from_python_int.dat"
fileobj = open(filename, mode='wb')
b = np.random.randint(100, size=(5,7))
b.tofile(fileobj)
fileobj.close
这将生成一个矩阵
[ [ 9 15 64 28 89 93 29]
[ 8 73 0 40 36 16 11]
[ 54 88 62 33 72 78 49]
[ 51 54 77 69 13 25 13]
[ 92 86 30 30 89 12 65] ]
但是当我从下面的 C 代码中读取它时:
#include <stdio.h>
#include <math.h>
int main()
{
/* later changed 'double' to 'int', but that still had issues */
double randn[5][7];
char buff[256];
FILE *latfile;
sprintf(buff,"%s","random_from_python_int.dat");
latfile=fopen(buff,"r");
fread(&(randn[0][0]),sizeof(int),35,latfile);
fclose(latfile);
printf("\n %d %d %d %d %d %d %d",randn[0][0],randn[0][1],randn[0][2],randn[0][3],randn[0][4],randn[0][5],randn[0][6]);
printf("\n %d %d %d %d %d %d %d",randn[1][0],randn[1][1],randn[1][2],randn[1][3],randn[1][4],randn[1][5],randn[1][6]);
printf("\n %d %d %d %d %d %d %d",randn[2][0],randn[2][1],randn[2][2],randn[2][3],randn[2][4],randn[2][5],randn[2][6]);
printf("\n %d %d %d %d %d %d %d",randn[3][0],randn[3][1],randn[3][2],randn[3][3],randn[3][4],randn[3][5],randn[3][6]);
printf("\n %d %d %d %d %d %d %d\n",randn[4][0],randn[4][1],randn[4][2],randn[4][3],randn[4][4],randn[4][5],randn[4][6]);
}
它会给我(调整空间以避免在 stackoverflow 网站上滚动):
28 15 64 93 29 -163754450 9
40 73 0 16 11 -163754450 8
33 88 62 17 91 -163754450 54
256 0 1830354560 0 4196011 -163754450 119
4197424 4197493 1826683808 4196128 2084711472 -163754450 12
我不确定出了什么问题。我已经尝试在 python 中编写一个浮点矩阵并在 C 中将其读取为 double,它工作正常。但是这个整数矩阵是行不通的。
【问题讨论】:
-
您将整数读入双精度数。
-
所以在整数与双重混淆之后,剩下的问题是:你怎么知道“整数”numpy 写入的大小与“int”C 使用的大小相同?
-
糟糕!但是在我将 double 更改为 int 之后,我得到了 9 0 15 0 64 0 28 0 89 0 93 0 29 0 8 0 73 0 0 0 40 0 36 0 16 0 11 0 54 0 88 0 62 0 33。
-
"你怎么知道 "integer" numpy 写入的大小与 "int" C 使用的大小相同" - 这是一个非常好的想法。你也许可以谷歌它。在 C 中,您可以通过使用类型 int32_t、int64_t 来强制设置大小
-
第一步:
latfile=fopen(buff,"r");-->latfile=fopen(buff,"rb");(加b)