I have the following snippet of C code:
#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.
How I can read this number in Python?
-
4Small tip: If you're transferring this binary file between computers, be sure to consider endianness and the size of your int.csl– csl2011年06月24日 09:05:05 +00:00Commented Jun 24, 2011 at 9:05
1 Answer 1
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.
Sign up to request clarification or add additional context in comments.
3 Comments
Léo Germond
You should replace '>' or '<' by '@' to use native endianess. Source: docs.python.org/library/…
johnsyweb
@Leo: Presuming the file is being read by the same machine (architecture) as the one that did the writing.
Léo Germond
@john, Yes tou are totally right about that, I was just "completing" your answer.
default