Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python read 16 bytes long double from binary file

Tags:

python

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.

like image 377
Peng Zhang Avatar asked Sep 28 '22 15:09

Peng Zhang


1 Answers

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)
like image 149
Ignacio Vazquez-Abrams Avatar answered Oct 07 '22 18:10

Ignacio Vazquez-Abrams