endian.h 1.8 KB

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