4

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?

1
  • 4
    Small tip: If you're transferring this binary file between computers, be sure to consider endianness and the size of your int. Commented Jun 24, 2011 at 9:05

1 Answer 1

3

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

You should replace '>' or '<' by '@' to use native endianess. Source: docs.python.org/library/…
@Leo: Presuming the file is being read by the same machine (architecture) as the one that did the writing.
@john, Yes tou are totally right about that, I was just "completing" your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.