简体   繁体   English

在Python中读取二进制文件中的整数

[英]Read integer from binary file in Python

I have the following snippet of C code: 我有以下C代码片段:

#include <stdio.h>
void main(){
  int a = 1308901095;
  FILE *fp;
  fp = fopen("file", "wb");
  fwrite(&a, sizeof(int), 1, fp);
  fclose(fp);
  printf("Done\n");
}

This will write the "a" integer in file "file", in binary form. 这将以二进制形式在文件“file”中写入“a”整数。

How I can read this number in Python? 我怎么能用Python读取这个数字?

Try following. 试试以下。

from struct import *
f = open('file', 'rb')
print unpack('<i', f.read(4))[0]
f.close()

note that using '<' about your machine is little endian or not. 请注意,关于您的机器使用'<'是小端或无。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM