Search code examples
c++arraysreinterpret-cast

Read 2D float array from binary, cast from char* to float[2]


I have a 2D array of floats stored in a binary file. I read it out using:

#include <fstream>
#include <algorithm>
....
ifstream infile(fileName.c_str(), ios::in | ios:binary);
const int numCols = 2;
char rows[1 * sizeof(int)];
infile.read(rows, sizeof(int));
int numRows = * reinterpret_cast<int *>(rows);
char * temp;
temp = new char[numRows * numCols * sizeof(float)];
infile.read(temp, sizeof(float) * numRows * numCols);

I then created the float array and used memcpy to copy the information over.

float binData[numRows][numCols];
memcpy(binData, temp, sizeof(float) * numRows * numCols); 

This approach works (binData contains what I want), but I'm being told not to use memcpy. So I changed to use this:

float * ftemp = reinterpret_cast<float *>(temp);
int loc;
for (int i = 0; i < numRows; ++i){
    for(int j = 0; j < numCols; ++j){
        loc = i * numCols + j;
        binData[i][j] = ftemp[loc];
    }
}

I tried using copy with ftemp and binData but I got this error:

incompatible types in assignment of 'float' to 'float [2]'

It seems overly complicated to use that double loop. Since the information is stored in the correct order in the char array there should be a way to say just read this as a float [numRows][numCols] or just copy the memory held in temp to binData but I can't figure it out. Is there a way to directly convert the char [] to a float [][] or is there an alternate char setup that will allow me to copy directly?


Solution

  • I'd just read straight into the array like this

    #include <fstream>
    #include <algorithm>
    ....
    ifstream infile(fileName.c_str(), ios::in | ios:binary);
    const int numCols = 2;
    int numRows;
    infile.read(reinterpret_cast<char *>(&numRows), sizeof(int));
    
    float (*binData)[numCols] = new float[numRows][numCols];
    //or float binData[numRows][numCols]; if you knew it can fit on the stack 
    //and your compiler has variable sized arrays
    
    //read into the array
    infile.read(reinterpret_cast<char *>(binData), sizeof(float) * numRows * numCols);