endian.h raw

   1  #ifndef _ENDIAN_H
   2  #define _ENDIAN_H
   3  
   4  #include <features.h>
   5  
   6  #define __NEED_uint16_t
   7  #define __NEED_uint32_t
   8  #define __NEED_uint64_t
   9  
  10  #include <bits/alltypes.h>
  11  
  12  #define __PDP_ENDIAN 3412
  13  
  14  #define BIG_ENDIAN __BIG_ENDIAN
  15  #define LITTLE_ENDIAN __LITTLE_ENDIAN
  16  #define PDP_ENDIAN __PDP_ENDIAN
  17  #define BYTE_ORDER __BYTE_ORDER
  18  
  19  static __inline uint16_t __bswap16(uint16_t __x)
  20  {
  21  	return __x<<8 | __x>>8;
  22  }
  23  
  24  static __inline uint32_t __bswap32(uint32_t __x)
  25  {
  26  	return __x>>24 | __x>>8&0xff00 | __x<<8&0xff0000 | __x<<24;
  27  }
  28  
  29  static __inline uint64_t __bswap64(uint64_t __x)
  30  {
  31  	return __bswap32(__x)+0ULL<<32 | __bswap32(__x>>32);
  32  }
  33  
  34  #if __BYTE_ORDER == __LITTLE_ENDIAN
  35  #define htobe16(x) __bswap16(x)
  36  #define be16toh(x) __bswap16(x)
  37  #define htobe32(x) __bswap32(x)
  38  #define be32toh(x) __bswap32(x)
  39  #define htobe64(x) __bswap64(x)
  40  #define be64toh(x) __bswap64(x)
  41  #define htole16(x) (uint16_t)(x)
  42  #define le16toh(x) (uint16_t)(x)
  43  #define htole32(x) (uint32_t)(x)
  44  #define le32toh(x) (uint32_t)(x)
  45  #define htole64(x) (uint64_t)(x)
  46  #define le64toh(x) (uint64_t)(x)
  47  #else
  48  #define htobe16(x) (uint16_t)(x)
  49  #define be16toh(x) (uint16_t)(x)
  50  #define htobe32(x) (uint32_t)(x)
  51  #define be32toh(x) (uint32_t)(x)
  52  #define htobe64(x) (uint64_t)(x)
  53  #define be64toh(x) (uint64_t)(x)
  54  #define htole16(x) __bswap16(x)
  55  #define le16toh(x) __bswap16(x)
  56  #define htole32(x) __bswap32(x)
  57  #define le32toh(x) __bswap32(x)
  58  #define htole64(x) __bswap64(x)
  59  #define le64toh(x) __bswap64(x)
  60  #endif
  61  
  62  #if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
  63  #if __BYTE_ORDER == __LITTLE_ENDIAN
  64  #define betoh16(x) __bswap16(x)
  65  #define betoh32(x) __bswap32(x)
  66  #define betoh64(x) __bswap64(x)
  67  #define letoh16(x) (uint16_t)(x)
  68  #define letoh32(x) (uint32_t)(x)
  69  #define letoh64(x) (uint64_t)(x)
  70  #else
  71  #define betoh16(x) (uint16_t)(x)
  72  #define betoh32(x) (uint32_t)(x)
  73  #define betoh64(x) (uint64_t)(x)
  74  #define letoh16(x) __bswap16(x)
  75  #define letoh32(x) __bswap32(x)
  76  #define letoh64(x) __bswap64(x)
  77  #endif
  78  #endif
  79  
  80  #endif
  81