0

I would like to export floating point numbers with a Python script into a binary file, and read the binary file with a C++ program, and interpret the bytes as floats. (On x86/IEEE754 machines. Without conversion. Just read data from a file and call it a float array.)

If I understand correctly Python uses floats that are the same as double in C. So 8 bytes. Is there a way to make this work? To export 4 byte floats from Python that will be the same representation as 4 byte floats in C++?

1
  • What Python actually uses is an implementation detail. CPython, though, will use whatever your machine's native double type is. Commented Nov 25, 2019 at 16:22

2 Answers 2

2

The array Python module allows you to dump your float array in one go:

import array
def dump_numbers(filename, numbers):
    with open(filename, 'wb') as fp:
        array.array('f', numbers).tofile(fp)
Sign up to request clarification or add additional context in comments.

Comments

2

The struct module takes care of this.

>>> import struct
>>> struct.pack("f", 3.14)  # 4-byte float
b'\xc3\xf5H@'
>>> struct.pack("g", 3.14)  # 8-byte double
b'\x1f\x85\xebQ\xb8\x1e\t@'

See the documentation for more information about how to control the endianness of the result.

Comments

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.