I'm trying to swap endianness in a big-endian file: my platform is little-endian, and so things are coming out wierd:
The first four bytes in the file correspond to a `float', but I couldn't use the binary operators `>>' or `<<' with a float on either side, which is why the signature has an "int&". Any suggestions for reading in the file as little-endian? I tried googling, but didn't get much.Code:#include <iostream> #include <fstream> using namespace std; // Endianness issue inline void endian_swap(int& x) { // Int is 4 bytes on this machine x = (x >> 24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24); } int main(int argc, char** argv) { const char * gcaf=argv[1]; const float GCA_VERSION=5.0; const int GCA_NO_MRF = 1; const int GIBBS_NEIGHBORHOOD=6; const int GIBBS_NEIGHBORS=GIBBS_NEIGHBORHOOD; const int MAX_LABELS=20; int * v = new int; ifstream GCA; GCA.open(gcaf, ifstream::binary); GCA.read((char*)v, sizeof(float)); endian_swap(v[0]); if (v[0] == GCA_VERSION) puts("hooray!"); else puts("darn"); // gives the wrong answer!!! cout << v[0] << '\n'; }



LinkBack URL
About LinkBacks


