Re: Byteswapping floating point types

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

 



On Tue, 2009-07-14 at 17:34 -0700, Ian Lance Taylor wrote:
> Andrew Troschinetz <ast@xxxxxxxxxxxxxxxx> writes:

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


I'd take it one step further, and make the byteswapped objects their own
types:

template<typename T> class Byteswapped
{
   unsigned char buf[sizeof(T)];
   T Unswap(void) const;
   void Swap(const T &t);

  public:
   operator T(void) const { return Unswap();}
   Byteswapped &operator =(const T &t) { Swap(t); return *this;}
   Byteswapped(const T&t) { Swap(t);}
   ~Byteswapped();
   ....
};

(forgive the incomplete class, but it's late where I am, and I've shut
down the C++ part of my brain for the night).

The idea is that you can then have the byteswapped types as distinct
types in the code, and can handle them as though they were the unswapped
types (albeit with a great deal of overhead). I've had to do this a
great deal in the embedded systems I design, where I have a very
heterogeneous mix of processors (ARM, PPC, x86, 56300 DSPs, TI C6x
DSPs).
This would also, in the case of a floating point value, keep the swapped
version from being treated by the CPU as a floating point value, and
should in theory keep it out of any FPU registers.




[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