[TriLUG] OT: network byte order double swapping

Ed Hill ed at eh3.com
Mon Apr 4 12:40:28 EDT 2005


On Mon, 2005-04-04 at 12:20 -0400, Brian Weaver wrote:
> Since a 'double' and a 'long long' are both the same number of bytes.
> You could do something like:
> 
> unsigned long long htonll(unsigned long long in)
> {
>     register unsigned long hold;
>     register unsigned long *p = (unsigned long *)∈
>     register unsigned long *q = p + 1;
> 
>     *p = htonl(*p);
>     *q = htonl(*q);
>     hold = *p;
>     *p = *q;
>     *q = hold;
> 
>     return in;
> }

The above looks like it will work on some machines, but IT IS NOT 64-bit
CLEAN AND THUS YOU SHOULD AVOID IT !!!  For instance, try:

cat > tst.c <<EOFF
#include "stdio.h"
int main (int argc, char ** argv)
{
   printf("sizeof(long) = %d\n",sizeof(long));
   printf("sizeof(unsigned long) = %d\n",sizeof(unsigned long));
   return 0;
}
EOF
make tst
./tst

on AMD64 (x86_64) system and see why.

In any case, as long as both machines are using IEEE-754 representations
(which basically everyone is) you don't have to worry about the mantissa
and exponent, you just have to swap the bytes:

  01234567  ==>  76543210

Ed

-- 
Edward H. Hill III, PhD
office:  MIT Dept. of EAPS;  Rm 54-1424;  77 Massachusetts Ave.
             Cambridge, MA 02139-4307
emails:  eh3 at mit.edu                ed at eh3.com
URLs:    http://web.mit.edu/eh3/    http://eh3.com/
phone:   617-253-0098
fax:     617-253-4464




More information about the TriLUG mailing list