如果文件是用 C 创建的,如何 read/write 从 python 中的二进制文件中浮动值
How to read/write float values from a binary file in python, if the file was created with C
如果二进制文件是用 C 语言创建的,我想 read/write C 浮点值?
文件是这样创建的:
#include <stdio.h>
int main() {
const int NUMBEROFTESTELEMENTS = 10;
/* Create the file */
float x = 1.1;
FILE *fh = fopen ("file.bin", "wb");
if (fh != NULL) {
for (int i = 0; i < NUMBEROFTESTELEMENTS; ++i)
{
x = 1.1*i;
fwrite (&x,1, sizeof (x), fh);
printf("%f\n", x);
}
fclose (fh);
}
return 0;
}
我found a method喜欢这样:
file=open("array.bin","rb")
number=list(file.read(3))
print (number)
file.close()
但这并不能保证读取的值是 C 浮点数。
import struct
with open("array.bin","rb") as file:
numbers = struct.unpack('f'*10, file.read(4*10))
print (numbers)
这应该可以完成工作。 numbers
是 10 个值中的 tuple
。
如果二进制文件是用 C 语言创建的,我想 read/write C 浮点值?
文件是这样创建的:
#include <stdio.h>
int main() {
const int NUMBEROFTESTELEMENTS = 10;
/* Create the file */
float x = 1.1;
FILE *fh = fopen ("file.bin", "wb");
if (fh != NULL) {
for (int i = 0; i < NUMBEROFTESTELEMENTS; ++i)
{
x = 1.1*i;
fwrite (&x,1, sizeof (x), fh);
printf("%f\n", x);
}
fclose (fh);
}
return 0;
}
我found a method喜欢这样:
file=open("array.bin","rb")
number=list(file.read(3))
print (number)
file.close()
但这并不能保证读取的值是 C 浮点数。
import struct
with open("array.bin","rb") as file:
numbers = struct.unpack('f'*10, file.read(4*10))
print (numbers)
这应该可以完成工作。 numbers
是 10 个值中的 tuple
。