endian.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #ifndef __MACHINE_ENDIAN_H__
  2. #define __MACHINE_ENDIAN_H__
  3. #include <sys/cdefs.h>
  4. #include <sys/_types.h>
  5. #include <machine/_endian.h>
  6. #if _BYTE_ORDER == _LITTLE_ENDIAN
  7. #define _QUAD_HIGHWORD 1
  8. #define _QUAD_LOWWORD 0
  9. #else
  10. #define _QUAD_HIGHWORD 0
  11. #define _QUAD_LOWWORD 1
  12. #endif
  13. #if __BSD_VISIBLE
  14. #define LITTLE_ENDIAN _LITTLE_ENDIAN
  15. #define BIG_ENDIAN _BIG_ENDIAN
  16. #define PDP_ENDIAN _PDP_ENDIAN
  17. #define BYTE_ORDER _BYTE_ORDER
  18. #endif
  19. #ifdef __GNUC__
  20. #define __bswap16(_x) __builtin_bswap16(_x)
  21. #define __bswap32(_x) __builtin_bswap32(_x)
  22. #define __bswap64(_x) __builtin_bswap64(_x)
  23. #else /* __GNUC__ */
  24. static __inline __uint16_t
  25. __bswap16(__uint16_t _x)
  26. {
  27. return ((__uint16_t)((_x >> 8) | ((_x << 8) & 0xff00)));
  28. }
  29. static __inline __uint32_t
  30. __bswap32(__uint32_t _x)
  31. {
  32. return ((__uint32_t)((_x >> 24) | ((_x >> 8) & 0xff00) |
  33. ((_x << 8) & 0xff0000) | ((_x << 24) & 0xff000000)));
  34. }
  35. static __inline __uint64_t
  36. __bswap64(__uint64_t _x)
  37. {
  38. return ((__uint64_t)((_x >> 56) | ((_x >> 40) & 0xff00) |
  39. ((_x >> 24) & 0xff0000) | ((_x >> 8) & 0xff000000) |
  40. ((_x << 8) & ((__uint64_t)0xff << 32)) |
  41. ((_x << 24) & ((__uint64_t)0xff << 40)) |
  42. ((_x << 40) & ((__uint64_t)0xff << 48)) | ((_x << 56))));
  43. }
  44. #endif /* !__GNUC__ */
  45. #ifndef __machine_host_to_from_network_defined
  46. #if _BYTE_ORDER == _LITTLE_ENDIAN
  47. #define __htonl(_x) __bswap32(_x)
  48. #define __htons(_x) __bswap16(_x)
  49. #define __ntohl(_x) __bswap32(_x)
  50. #define __ntohs(_x) __bswap16(_x)
  51. #else
  52. #define __htonl(_x) ((__uint32_t)(_x))
  53. #define __htons(_x) ((__uint16_t)(_x))
  54. #define __ntohl(_x) ((__uint32_t)(_x))
  55. #define __ntohs(_x) ((__uint16_t)(_x))
  56. #endif
  57. #endif /* __machine_host_to_from_network_defined */
  58. #endif /* __MACHINE_ENDIAN_H__ */