endian.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #ifndef _ENDIAN_H
  2. #define _ENDIAN_H
  3. #if __STDC_VERSION__ >= 199901L || defined(__cplusplus)
  4. #define __inline inline
  5. #endif
  6. #define __LITTLE_ENDIAN 1234
  7. #define __BIG_ENDIAN 4321
  8. #define __PDP_ENDIAN 3412
  9. #if defined(__GNUC__) && defined(__BYTE_ORDER__)
  10. #define __BYTE_ORDER __BYTE_ORDER__
  11. #else
  12. #include <bits/endian.h>
  13. #endif
  14. #if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
  15. #define BIG_ENDIAN __BIG_ENDIAN
  16. #define LITTLE_ENDIAN __LITTLE_ENDIAN
  17. #define PDP_ENDIAN __PDP_ENDIAN
  18. #define BYTE_ORDER __BYTE_ORDER
  19. #include <stdint.h>
  20. static __inline uint16_t __bswap16(uint16_t __x)
  21. {
  22. return __x<<8 | __x>>8;
  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. static __inline uint64_t __bswap64(uint64_t __x)
  29. {
  30. return __bswap32(__x)+0ULL<<32 | __bswap32(__x>>32);
  31. }
  32. #if __BYTE_ORDER == __LITTLE_ENDIAN
  33. #define htobe16(x) __bswap16(x)
  34. #define be16toh(x) __bswap16(x)
  35. #define betoh16(x) __bswap16(x)
  36. #define htobe32(x) __bswap32(x)
  37. #define be32toh(x) __bswap32(x)
  38. #define betoh32(x) __bswap32(x)
  39. #define htobe64(x) __bswap64(x)
  40. #define be64toh(x) __bswap64(x)
  41. #define betoh64(x) __bswap64(x)
  42. #define htole16(x) (uint16_t)(x)
  43. #define le16toh(x) (uint16_t)(x)
  44. #define letoh16(x) (uint16_t)(x)
  45. #define htole32(x) (uint32_t)(x)
  46. #define le32toh(x) (uint32_t)(x)
  47. #define letoh32(x) (uint32_t)(x)
  48. #define htole64(x) (uint64_t)(x)
  49. #define le64toh(x) (uint64_t)(x)
  50. #define letoh64(x) (uint64_t)(x)
  51. #else
  52. #define htobe16(x) (uint16_t)(x)
  53. #define be16toh(x) (uint16_t)(x)
  54. #define betoh16(x) (uint16_t)(x)
  55. #define htobe32(x) (uint32_t)(x)
  56. #define be32toh(x) (uint32_t)(x)
  57. #define betoh32(x) (uint32_t)(x)
  58. #define htobe64(x) (uint64_t)(x)
  59. #define be64toh(x) (uint64_t)(x)
  60. #define betoh64(x) (uint64_t)(x)
  61. #define htole16(x) __bswap16(x)
  62. #define le16toh(x) __bswap16(x)
  63. #define letoh16(x) __bswap16(x)
  64. #define htole32(x) __bswap32(x)
  65. #define le32toh(x) __bswap32(x)
  66. #define letoh32(x) __bswap32(x)
  67. #define htole64(x) __bswap64(x)
  68. #define le64toh(x) __bswap64(x)
  69. #define letoh64(x) __bswap64(x)
  70. #endif
  71. #endif
  72. #endif