Size-independent byte order swapping functions.
Luigi Rizzo
rizzo at icir.org
Tue Feb 3 02:48:47 PST 2004
On Tue, Feb 03, 2004 at 11:38:04AM +0100, Pawel Jakub Dawidek wrote:
...
> +> I have a hard time seeing a sensible use for these.
> +>
> +> Endianess conversion is almost exclusively used in communications
> +> (even if the "transmission media" is a disk), and I can't possibly
> +> see how it can make sense to be lax about wordsize but strict about
> +> byteordering.
in fact, i'd rather have some types that prevent you from
making mistakes and carelessly copy values between incompatible types.
I am exploring ways to do this -- e.g. at the moment i am using this:
#define N(x) ((x).__x)
#define H16(x) (ntohs(N(x)))
#define H32(x) (ntohl(N(x)))
#define N16(x) (htons(x))
#define N32(x) (htonl(x))
struct _n32_t {
uint32_t __x;
};
struct _n16_t {
uint16_t __x;
};
typedef struct _n32_t n32_t; /* network format */
typedef struct _n16_t n16_t; /* network format */
so that the compiler prevents me from assigning between
host and network representations.
uint32_t a, b;
n32_t c, d;
c = d; /* ok */
a = b; /* ok */
c = b; /* compiler complains */
N(c) = N32(b); /* ok */
b = H32(c); /* ok */
c == b; /* unfortunately does not work */
N(c) == N(b); /* ok, saves conversion */
H32(c) == H32(b); /* ok, requires conversion */
of course, the use of custom macros probably makes the code less
readable once one is used to the ntoh*() stuff...
cheers
luigi
More information about the freebsd-arch
mailing list