Faced the following function, the author uses it when writing data to a .vtk file. Tell me, what does this feature do?

template <typename T> void SwapEnd(T& var) { char* varArray = reinterpret_cast<char*>(&var); for (long i = 0; i < static_cast<long>(sizeof(var) / 2); i++) std::swap(varArray[sizeof(var) - 1 - i], varArray[i]); } 

    1 answer 1

    Changes the byte order in a variable. Only the variable should be POD, which, alas, is not checked - otherwise there will be trouble ...

    For example,

     unsigned long L = 0xDEADBEEF; cout << hex << L << endl; SwapEnd(L); cout << hex << L << endl; 

    displays

     deadbeef efbeadde 

    Just with the usual C-string, by the way, there will also be problems ... Even if it is transmitted as an array, the null character will also participate in the exchange.