10 November 2011

htonll - 64bit host to network conversion

See difference in output for little endian and big endian machines (bswap64.c)

Constant folding is the process of simplifying constant expressions at compile time.
With constant folding support, i = 1 * 2 * 3 * 4 * 5; is calculated at compile time, i = 120.
#include <endian.h>

typedef unsigned long long uint64;
typedef unsigned long uint32;

typedef union {
  uint64 big;
  uint32 small[2];
}long_long;

#define HTONLL01(x) ({long_long i; i.small[0] = htonl((uint32)(x>>32)); \
                      i.small[1] = htonl((uint32)x); x = i.big;})

#if __BYTE_ORDER == __BIG_ENDIAN
# define HTONLL02(x) (x)
#else
# if __BYTE_ORDER == __LITTLE_ENDIAN
#  define HTONLL02(x) (((uint64)htonl((uint32)x))<<32 | htonl((uint32)(x>>32)))
# endif
#endif

From "/usr/include/bits/byteswap.h"
/* Swap bytes in 64 bit value.  */
#define __bswap_constant_64(x) \
     (  (((x) & 0xff00000000000000ull) >> 56)                     \
      | (((x) & 0x00ff000000000000ull) >> 40)                     \
      | (((x) & 0x0000ff0000000000ull) >> 24)                     \
      | (((x) & 0x000000ff00000000ull) >> 8)                      \
      | (((x) & 0x00000000ff000000ull) << 8)                      \
      | (((x) & 0x0000000000ff0000ull) << 24)                     \
      | (((x) & 0x000000000000ff00ull) << 40)                     \
      | (((x) & 0x00000000000000ffull) << 56))

# define __bswap_64(x) \
     (__extension__                                               \
      ({ union { __extension__ unsigned long long int __ll;       \
         unsigned long int __l[2]; } __w, __r;                    \
     if (__builtin_constant_p (x))                                \
       __r.__ll = __bswap_constant_64 (x);                        \
     else                                                         \
       {                                                          \
         __w.__ll = (x);                                          \
         __r.__l[0] = __bswap_32 (__w.__l[1]);                    \
         __r.__l[1] = __bswap_32 (__w.__l[0]);                    \
       }                                                          \
     __r.__ll; }))

Reference:
http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/
http://en.wikipedia.org/wiki/Constant_folding

No comments:

Post a Comment