I am trying translate a code from Matlab into C++. I am stuck at the most basic of steps: loading in a data file of int16. I know how to do it Matlab (its just one line of code). I even did it in C (although I still don't know how I got that to work, but it does). Any suggestions would be greatly appreciated.
#include <stdio.h>
int main () {
FILE *header;
union twobytes // I found this method online and adapted it
{
int intvalue;
char byte [sizeof (int)];
} bytes;
int lSize;
int result;
int i;
header=fopen("filepath/file.hdr","rb"); // it is an .hdr file
fseek (header, 0, SEEK_END);
lSize = ftell (header);
printf("file size %i\n",lSize); // size of the file
rewind (header); // go back to start
char buffer[4];
for(i=0;i<24;i++){ // only need first 25 values
result=fread (buffer, 2, 1, header); // no idea why it is 1 and not 2, but 2 didn't work
printf("buffer is:%i\n",*buffer); // this buffer actually give me 92 if I print it to screen without the below modification. the same value as the first output in the C++ code
bytes.byte[0] = buffer[0];
bytes.byte[1] = buffer[1];
bytes.byte[2] = 0; // no idea why but this is necessary for it to work
bytes.byte[3] = 0;
printf ("\nbytes.intvalue: %i\n", bytes.intvalue);
}
fclose(header);
return 0;
}
It is so much easier to do in Matlab, but I am working with 3D images and need to move the code to something with better memory. I am trying to read in the header file with the dimensions of the image matrix. I have been working on this for two days and cannot figure it out! It has been great to learn more about C++ coding, I just wish I knew as much about coding in it as I do about Matlab.
istream::get() reads only one byte. You need to read two. Your other codes will fail if you try to load negative int16_t's. It will also fail if you try to compile on a system using a different endianness.
1 2 3 4
int16_t n = 0;
n |= (unsignedchar)ifs.get();
n |= ifs.get() << 8;
cout << n << endl;