Python read 16 bytes long double from binary

I find that python struct.unpack() quite convenient for reading binary data generated by other programs.

Question: How to read a 16-byte long double from a binary file?

The following C code writes 1.01 three times to the binary using a 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 float and double without problems.

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

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

+5
source share
1 answer

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

 f128 = numpy.frombuffer(file.read(16), dtype=numpy.float128) 
+4
source

Source: https://habr.com/ru/post/1214352/


All Articles