Simple tools for networking / objects in plain C Snapshot
endutil.h
Go to the documentation of this file.
00001 #ifndef __ENDIAN_H_Y_Z__
00002 #define __ENDIAN_H_Y_Z__
00003 
00004 #include <cutils/base.h>
00005 #include <arpa/inet.h>
00006 
00007 
00008 /**
00009  * @defgroup ENDIAN
00010  * @brief normalize the names of endian conversion functions, so that they can be used from macros.
00011  * 
00012  * n2h_<typename> - convert from network to host byte order
00013  * h2n_<typename> - convert from host to network byte order.
00014  *
00015  * <typename> := int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_ta
00016  *
00017  * @{
00018  */
00019 
00020 typedef union {
00021   struct {
00022      uint32_t word_a;
00023      uint32_t word_b;
00024   } n32;
00025   uint64_t n64;
00026 } QUAD;
00027 
00028 M_INLINE uint64_t n2h_uint64_t(uint64_t val)
00029 {
00030   QUAD a,b;
00031   
00032   a.n64 = val;
00033 
00034   b.n32.word_a = ntohl( a.n32.word_b );
00035   b.n32.word_b = ntohl( a.n32.word_a );
00036 
00037   return b.n64;
00038 }
00039 
00040 M_INLINE uint64_t h2n_uint64_t(uint64_t val)
00041 {
00042   QUAD a,b;
00043   
00044   a.n64 = val;
00045 
00046   b.n32.word_a = htonl( a.n32.word_b );
00047   b.n32.word_b = htonl( a.n32.word_a );
00048 
00049   return b.n64;
00050 }
00051 
00052 
00053 #define n2h_uint8_t(val)  (val)
00054 #define n2h_int8_t(val)   (val)
00055 #define n2h_uint16_t(val) ntohs( val )
00056 #define n2h_int16_t(val)  ntohs( val )
00057 #define n2h_uint32_t(val) ntohl( val )
00058 #define n2h_int32_t(val)  ntohl( val )
00059 #define n2h_int64_t(val)  n2h_uint64_t( val )
00060 
00061 #define h2n_uint8_t(val)  (val)
00062 #define h2n_int8_t(val)   (val)
00063 #define h2n_uint16_t(val) htons( val )
00064 #define h2n_int16_t(val)  htons( val )
00065 #define h2n_uint32_t(val) htonl( val ) 
00066 #define h2n_int32_t(val)  htonl( val )
00067 #define h2n_int64_t(val)  h2n_uint64_t( val ) 
00068 
00069 /**
00070  * @}
00071  */
00072  
00073 #endif
00074