Cool_Coder
Cool_Coder

Reputation: 5073

Portable binary file for storing double in C++

Let us consider 2 PC's: PC A which requires 64 bit (8 bytes) to store a double variable and PC B which requires 128 bit (16 bytes) to store a double variable. A binary file is created in using my application on A. The file is copied to B and my program is reading the file. Let us consider the file contains 10 double variables. To illustrate the file contains information like this:

8888888888

//8 represents 8 bytes

Now when B is reading it will see the data as

1616161616

//so it reads only 5 variables instead of 10 and that too incorrect values will be stored in these variables.

So my question is, how do you manage the read/write such that the above situations do not occur such that

  1. The data can only be stored in a binary file
  2. The data is stored by the appication in double[] and it cannot be converted to strings because there are millions of double variables in real life situations and translation time is too much

I tried by reading the data in char * of appropriate length. But when the char * is converted to double by reinterpret_cast the double has garbage value.

Upvotes: 1

Views: 615

Answers (1)

Robin Green
Robin Green

Reputation: 33063

Use an existing serialization library such as protobuf, or the newer cap'nproto (which optimizes for the most common use-case).

Upvotes: 2

Related Questions