Reputation: 75
I don't normally work with binary files so I apologize if the answer to this is obvious. I am able to read fine from a certain binary file using the following command:
nread = fread(&data[0],sizeof(float),maxpts,fptr);
The binaries are a standardized scientific format and it seems that the data is stored as floats. I would prefer to read this data into an array of type double however, and when I try to simply switch the type of data to double (from float), and leave sizeof(float) the same, it doesn't retrieve my data correctly. How would I go about doing this? Thanks, Zach.
Upvotes: 1
Views: 513
Reputation: 16195
You could read the data in as float precision, then allocate an array of doubles and then manually fill the array of doubles using a for loop.
See one of my old questions How can I perform conversion from float -> double -> float when processing an audio buffer in c++
Basically . .
doubleArray=malloc(numElements*sizeof(double));
for (int nn=0; nn<numElements; ++nn)
{
doubleArray[nn] = floatArray[nn];
}
Upvotes: 2
Reputation:
You will need to read the data as floats and convert it to doubles by bulk assignment (e.g, read into an array of floats, have a separate array of doubles, and, for each element, set doubleArray[i] = floatArray[i]
).
There are ways that you could accelerate this process (by making use of specific facts about the storage of floats and doubles), but it's probably not worth it, especially as it may introduce subtle inaccuracies.
Upvotes: 3