endian.h 1.9 KB

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