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

Re: Big-endian/little-endian



Hi,

> The authors concern was that on a big endian system network order and
> byte order are the same so hton* and ntoh* do nothing....so how do you
> do the swapps...

You could just cast the address of the variable to a "char *" and swap
things around using pointer arithmetic or arrays.  Here is a sample piece
of C++ code (it should be easy to modify for C):

	// "number" is the size of the array being byte swapped
	swap4(void *dest, void *src, int number) {
	  unsigned char *t = (unsigned char *)dest;
	  unsigned char *s = (unsigned char *)src;
	  if( t == s ) {
	    for (int i = 0; i < number; ++i, t += 4) {
	      unsigned char tmp;
	      tmp = *t;     *t = t[3]; t[3] = tmp;
	      tmp = t[1]; t[1] = t[2]; t[2] = tmp;
	    }
	  }
	  else
	    for (int i = 0; i < number; ++i, t += 4) {
	      t[3] = *s++; t[2] = *s++; t[1] = *s++; *t = *s++; }
	}

This may not be the best way to do the byte swapping but it is fairly
straight forward to do it this way.  However, it may not be very
efficient.  Of course, if you're not swapping entire arrays then this may
be a decent solution.

-Ossama


Reply to: