> Andrew Troschinetz <ast@xxxxxxxxxxxxxxxx> writes: > >> template<class T> >> T byteswap(T value) >> { >> T result; >> size_t n = sizeof (T); >> unsigned char* p = (unsigned char*) &value; >> for (size_t i = 0; i < n; ++i) >> ((unsigned char*) &result)[i] = p[n - 1 - i]; >> return result; >> } > > I would avoid aliasing issues and the problem you describe and write the > code like this (untested): > > template<typename T> > T byteswap(T value) > { > char buf1[sizeof(T)], buf2[sizeof(T)]; > memcpy(buf1, &value, sizeof(T)); > for (size_t i = 0; i < sizeof(T); ++i) > buf2[i] = buf1[sizeof(T) - 1 - i]; > T ret; > memcpy(&ret, buf2, sizeof(T)); > return ret; > } Tested here: http://codepad.org/JGKW3ir0 Unfortunately this code does not avoid the issue. Since the function still returns a T, when T is a floating point type you are putting a byteswapped floating point value into a floating point type. At which point I contend that you risk the data being modified. My co-worker maintains that the risk is only present on broken compilers and when people try to do things to swapped floats that they shouldn't be doing (ie: he passes the blame on to either the compiler or the programmer, not to his byteswap() function). Within that code paste I present a solution which sidesteps the issue by returning a sequence of bytes, so that a byteswapped floating point value never has the chance to go into a FPU register. However the solution I present is significantly less convenient to use than my co-workers so I think we're both hoping that he's right and I'm wrong. (Scratch that I totally want to be proven right on this :) > On some processors this can convert a valid floating point > representation into a trap representation which will cause a floating > point exception if the value is used. Presumably that is not an issue > for you. I think it could be an issue for us (if not now then maybe in the future), which is why I've raised concern over byteswap() as my co-worker has implemented it. -- Andrew Troschinetz Applied Research Laboratories