I’m working with fits images using C++. This format can hold 8/16/32 bits integers and 32/64 bits floating point arrays. The pixel size (variable type) is contained given by a header flag.
When I read one of this images using cfitsio library [http://heasarc.gsfc.nasa.gov/fitsio/] I get a char array that holds all the pixels of the image:
char* array = new char[npix*bytepix]; // bytepix is the number of bytes per pixel
fits_read_img(infptr, datatype, first, npix, &nulval, lArray, &anynul, &status);
I can then get the “true” value of the pixel by a type cast. I.E. to get the value of the ith pixel for a 32 bits integer I would do:
int32_t pixelValue = ((int32_t*) lArray)[i];
I would like to know what is the most compact way of dealing with this in general, as I don’t know what the pixel type will be when I write the code.
What I currently do is something like this:
switch(bytepix){
case 1:{
int8_t *vecVal = ((int8_t*) array );
}
break;
case 2:{
int16_t *vecVal = ((int16_t*) array );
}
break;
case 4:{
int32_t *vecVal = ((int32_t*) array );
}
break;
case 8:{
int64_t *vecVal = ((int64_t*) array );
}
break;
default:
cout << "error\n";
break;
}
}
That is clearly ugly and not very flexible.
Thanks a lot for your help!
What you’re trying to do is called generic programming. It’s a fundamental concept that splits the algorithm and the types it operates on. It is supported in C++ with template functions and template classes, and the whole C++ Standard Template Library is based upon it.
Basically, implement your processing function independently of the FITS pixel size:
And then call it with the respective pixel size:
A couple of thoughts: