I have a 3D-volume, represented as as vector of vector of vector of float, that I want to save to a binary file. (It's a density volume reconstructed from X-ray images that come from a CT scanner.)
Now, I could do this in the following way:
//iterate through the volume
for (int x = 0; x < _xSize; ++x){
for (int y = 0; y < _ySize; ++y){
for (int z = 0; z < _zSize; ++z){
//save one float of data
stream.write((char*)&_volume[x][y][z], sizeof(float));
}
}
}
This basically works. However, I'm asking myself to which extent this is platform independent. I would like to produce a file which is identical regardless of the system it was created on. So there might be machines running Windows, Linux or Mac, they might have 32bit or 64bit word lenght and little endian or big endian byte order.
I suppose if I did this the way it was done above this wouldn't be the case. Now how could I achieve this? I've heard about serialisation but I haven't found a concrete solution for this instance.
I solved the problem using the Qt Datastream
class. Qt is part of my project anyway, so the additional effort is minimal. I can tell the Datastream
object exactly if I want to save my floats
using single precision (32bit) or double precision (64bit) and if I want to use little endian or big endian byte order. This is totally sufficient for what I need; I don't need to serialize objects. The files I save now have exactly the same format on all platforms (at least they should), and this is all I need. They will afterwards be read by 3rd party applications to which these information (byte order, precision) will be supplied. So to say it is not of importance exactly how my floats are saved but that I know how they are saved and that this is consistent no matter on which platform you run the program.
Here is how the code looks now:
QDataStream out(&file);
out.setFloatingPointPrecision(QDataStream::SinglePrecision);
out.setByteOrder(QDataStream::LittleEndian);
for (int x = 0; x < _xSize; ++x){
for (int y = 0; y < _ySize; ++y){
for (int z = 0; z < _zSize; ++z){
//save one float of data
out<<_volume[x][y][z];
}
}
}