5

I find python struct.unpack() is quite handy to read binary data generated by other programs.

Question: How to read 16-bytes long double out of a binary file?

The following C code writes 1.01 three times to a binary file, using 4-byte float, 8-byte double and 16-byte long double respectively.

FILE* file     = fopen("test_bin.bin","wb");
float f        = 1.01;
double d       = 1.01;
long double ld = 1.01;
fwrite(&f, sizeof(f),1,file);
fwrite(&d, sizeof(d),1,file);
fwrite(&ld, sizeof(ld),1,file);                     
fclose(file);

In python, I can read the float and double with no problem.

file=open('test_bin.bin','rb')
struct.unpack('<fd',file.read(12)) # (1.0099999904632568, 1.01) as expected.

I do not find description of 16-byte long double in module struct format character section.

Peng Zhang
  • 3,475
  • 4
  • 33
  • 41

1 Answers1

4

Python does not support binary128s natively, hence you won't find support for them in the standard library. You will need to use NumPy (specifically numpy.frombuffer()) to convert from bytes to a binary128.

f128 = numpy.frombuffer(file.read(16), dtype=numpy.float128)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358