Write binary in C++ and read it in Python

In this tutorial, I am going to show you how to write binary in C++ programming and then read it using Python.

To write binary data in C++ and read it in Python, you need to ensure that both of the programs agree on the format of the data being written and read. Here is given a basic example to illustrate this process:

C++: Writing Binary Data

In C++, you can use the ofstream to write binary data to a file. below is given how to do it:

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outFile("data.bin", std::ios::binary);

    if (!outFile) {
        std::cerr << "Error opening file for writing.\n";
        return 1;
    }

    int data = 12345; // Example data to write
    outFile.write(reinterpret_cast<char*>(&data), sizeof(data));

    outFile.close();
    return 0;
}

This code writes an integer (12345) to a file named data.bin in binary format.

Python: Reading Binary Data

In Python, you can read the binary data using open with the 'rb' mode:

with open('data.bin', 'rb') as file:
    data = file.read()
    number = int.from_bytes(data, byteorder='little', signed=True)

print(number)

This Python script reads the binary data from data.bin and converts it to an integer. The byteorder should match the endianness of the system where the C++ code is running. In this case, I assumed a little-endian system, which is common.

Important Considerations

Below are some important considerations that a programmer should take into account:

  1. Data Types and Sizes: Ensure that the data types and their sizes match in both C++ and Python. Different systems or compilers might have different sizes for the same data types (like int).
  2. Endianness: Binary data is sensitive to the byte order (endianness). If the writing and reading systems have different endianness, you need to account for that.
  3. Error Handling: Add appropriate error handling for file operations in both C++ and Python.
  4. Complex Data: For more complex data structures, consider using a serialization library or a common data format like JSON or Protocol Buffers, though this might not be suitable for all binary data needs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top