endian.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <sys/cdefs.h>
  8. __BEGIN_DECLS
  9. #define __LITTLE_ENDIAN 1234
  10. #define __BIG_ENDIAN 4321
  11. #define __PDP_ENDIAN 3412
  12. #if defined(__GNUC__) && defined(__BYTE_ORDER__)
  13. # define __BYTE_ORDER __BYTE_ORDER__
  14. #else
  15. # include <bits/endian.h>
  16. #endif
  17. #if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
  18. # include <stdint.h>
  19. static __inline uint16_t __bswap16(uint16_t x)
  20. {
  21. return __builtin_bswap16(x);
  22. }
  23. static __inline uint32_t __bswap32(uint32_t x)
  24. {
  25. return __builtin_bswap32(x);
  26. }
  27. static __inline uint64_t __bswap64(uint64_t x)
  28. {
  29. return __builtin_bswap64(x);
  30. }
  31. # define LITTLE_ENDIAN __LITTLE_ENDIAN
  32. # define BIG_ENDIAN __BIG_ENDIAN
  33. # define PDP_ENDIAN __PDP_ENDIAN
  34. # define BYTE_ORDER __BYTE_ORDER
  35. # if __BYTE_ORDER == __LITTLE_ENDIAN
  36. # define htole16(x) ((uint16_t)(x))
  37. # define le16toh(x) ((uint16_t)(x))
  38. # define letoh16(x) ((uint16_t)(x))
  39. # define htole32(x) ((uint32_t)(x))
  40. # define le32toh(x) ((uint32_t)(x))
  41. # define letoh32(x) ((uint32_t)(x))
  42. # define htole64(x) ((uint64_t)(x))
  43. # define le64toh(x) ((uint64_t)(x))
  44. # define letoh64(x) ((uint64_t)(x))
  45. # define htobe16(x) (__builtin_bswap16(x))
  46. # define be16toh(x) (__builtin_bswap16(x))
  47. # define betoh16(x) (__builtin_bswap16(x))
  48. # define htobe32(x) (__builtin_bswap32(x))
  49. # define be32toh(x) (__builtin_bswap32(x))
  50. # define betoh32(x) (__builtin_bswap32(x))
  51. # define htobe64(x) (__builtin_bswap64(x))
  52. # define be64toh(x) (__builtin_bswap64(x))
  53. # define betoh64(x) (__builtin_bswap64(x))
  54. # else
  55. # define htole16(x) (__builtin_bswap16(x))
  56. # define le16toh(x) (__builtin_bswap16(x))
  57. # define letoh16(x) (__builtin_bswap16(x))
  58. # define htole32(x) (__builtin_bswap32(x))
  59. # define le32toh(x) (__builtin_bswap32(x))
  60. # define letoh32(x) (__builtin_bswap32(x))
  61. # define htole64(x) (__builtin_bswap64(x))
  62. # define le64toh(x) (__builtin_bswap64(x))
  63. # define letoh64(x) (__builtin_bswap64(x))
  64. # define htobe16(x) ((uint16_t)(x))
  65. # define be16toh(x) ((uint16_t)(x))
  66. # define betoh16(x) ((uint16_t)(x))
  67. # define htobe32(x) ((uint32_t)(x))
  68. # define be32toh(x) ((uint32_t)(x))
  69. # define betoh32(x) ((uint32_t)(x))
  70. # define htobe64(x) ((uint64_t)(x))
  71. # define be64toh(x) ((uint64_t)(x))
  72. # define betoh64(x) ((uint64_t)(x))
  73. # endif
  74. #endif
  75. __END_DECLS