Subject: Re: hton64
To: John F. Woods <jfw@jfwhome.funhouse.com>
From: Johan Danielsson <joda@pdc.kth.se>
List: current-users
Date: 06/30/1997 05:18:57
--Multipart_Mon_Jun_30_05:18:57_1997-1
Content-Type: text/plain; charset=US-ASCII

"John F. Woods" <jfw@jfwhome.funhouse.com> writes:

> (htonXX and friends are, I think, perfectly good candidates for
> being machine-dependant.)

The following will octet-swap on `anything', in a C9x compatible way.

/Johan


--Multipart_Mon_Jun_30_05:18:57_1997-1
Content-Type: text/plain; charset=US-ASCII

#include <inttypes.h>

/* a is the value to swap, and n is 
   the number of octets to swap */

uintmax_t
_swapN(uintmax_t a, unsigned n)
{
    uintmax_t b = 0;
    while (a && n) {
	n--;
	b |= (a & 0xff) << (8 * n);
	a >>= 8;
    }
    return b;
}

#define _SWAP(N)				\
uint ## N ## _t _swap ## N (uint ## N ## _t a)	\
{ 						\
    return _swapN(a, (N) / 8); 			\
}

#ifdef UINT16_MAX
_SWAP(16)
#endif
#ifdef UINT32_MAX
_SWAP(32)
#endif
#ifdef UINT64_MAX
_SWAP(64)
#endif

--Multipart_Mon_Jun_30_05:18:57_1997-1--