Quote:Original post by samuraicrow
If you're using SDL then use its built-in endian swapper/reader:
*** Source Snippet Removed ***
or something similar. SDL's endian swapping routines are optimized for maximum performance under most processors and use inline assembly to accomplish this feat.
That's quite broken. For one thing, you're C-style casting. For another, you're casting the array address (char*) to the int, rather than a pointer thereto. You'll be swapping the bytes of *the location in memory* of the array, rather than the content bytes.
Anyway.
#ifdef SWAP_ENDIANtemplate <typename POD>void fill_from_buffer(char* buffer, POD& target) { typedef reverse_iterator<char*, char> ri; std::fill(ri(buffer), ri(buffer + sizeof(POD)), reinterpret_cast<char*>(&target));}#elsetemplate <typename POD>void fill_from_buffer(char* buffer, POD& target) { std::fill(buffer, buffer + sizeof(POD), reinterpret_cast<char*>(&target));}#endiftemplate <typename POD>POD create_from_buffer(char* buffer) { POD result; fill_from_buffer(buffer, result); return result;}
That is, instead of trying to interpret the few bytes as an int, interpret the location of the int as a place where bytes can be written.