Re: Byteswapping floating point types

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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;
}

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.

Ian

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux