endian.h 2.0 KB

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