endian.h 2.0 KB

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