From: Giulio Guarnone on 5 Aug 2010 19:24 On 6 Ago, 05:36, red floyd <redfl...(a)gmail.com> wrote: > On Aug 5, 1:00 pm, Giulio Guarnone <giulio.guarn...(a)gmail.com> wrote: > > > >> Hi to all, > >> I've written down this function for perfoming endian conversion : > >> template<typename T> >> T swap_endian(const T& source) >> { >> T ret = 0; > >> for (int i = 0; i < sizeof(T); ++i) >> { >> *(reinterpret_cast<char*>(&ret) + i) = >> *(reinterpret_cast<char*>(&source) + sizeof(T) - i - 1); >> } >> return ret; > >> } > >> It seems to work the most of the times, but I'm not sure when I use it >> on signed types (int long etc etc) with negative numbers or with >> positive numbers like 1520 : > >> bigendian 0x05F0 >> littleendian 0xF005 > >> Is it correct, or has anyone a better routine ? > > It looks to me like you're swapping each byte *twice*. > > I think your loop should only go to sizeof(T)/2 I've tried this function (the right declaration is T swap_endian(T& source); ) and it seems to work with the "regular" cases. I'm in doubt for the "special" cases I've reported. Thanx -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: K. Opreschko on 5 Aug 2010 19:48 Hi Giulio, I adapted the function I use for endian conversions to your template, I hope it would be helpful. template<typename T> void swap_endian(T& source) { char* chr_ptr = reinterpret_cast<char*>(&source); for (int i = 0; i < sizeof(T) / 2; ++i) { chr_ptr[i] ^= chr_ptr[sizeof(T) - 1 - i]; chr_ptr[sizeof(T) - 1 - i] ^= chr_ptr[i]; chr_ptr[i] ^= chr_ptr[sizeof(T) - 1 - i]; } } It works with the "source" variable directly, without using the "ret" intermediate variable. Also, it is possible to swap variables of any length. Best regards, Klaus Opreschko -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Nick Hounsome on 6 Aug 2010 19:13
On 5 Aug, 21:00, Giulio Guarnone <giulio.guarn...(a)gmail.com> wrote: > Hi to all, > > I've written down this function for perfoming endian conversion : > > template<typename T> > T swap_endian(const T& source) IMHO The design is dubious because it implicitly gives a single variable two different meanings depending on where you ask: int height = 185; // height is my height in cm swap_endian(height); // height is what? Another issue that I came across when using templates is that it is easy to accidentally mess things up by changing the type or by porting to a different machine. I prefer to be explicit, let the compuiler warn me and delay until the last moment: EncodeUint16( ENDIAN_BE16(height) ); // My protcol requires a big endian 16 bit quantity height = ENDIAN_BE16( DecodeUint16() ); // My protocol supplies a big endian 16 bit quantity -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |