byteswap.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Macros and inline functions to swap the order of bytes in integer values.
  2. Copyright (C) 1997-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #if !defined _BYTESWAP_H && !defined _NETINET_IN_H && !defined _ENDIAN_H
  16. # error "Never use <bits/byteswap.h> directly; include <byteswap.h> instead."
  17. #endif
  18. #ifndef _BITS_BYTESWAP_H
  19. #define _BITS_BYTESWAP_H 1
  20. #include <features.h>
  21. #include <bits/types.h>
  22. /* Swap bytes in 16-bit value. */
  23. #define __bswap_constant_16(x) \
  24. ((__uint16_t) ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8)))
  25. static __inline __uint16_t
  26. __bswap_16 (__uint16_t __bsx)
  27. {
  28. #if __GNUC_PREREQ (4, 8)
  29. return __builtin_bswap16 (__bsx);
  30. #else
  31. return __bswap_constant_16 (__bsx);
  32. #endif
  33. }
  34. /* Swap bytes in 32-bit value. */
  35. #define __bswap_constant_32(x) \
  36. ((((x) & 0xff000000u) >> 24) | (((x) & 0x00ff0000u) >> 8) \
  37. | (((x) & 0x0000ff00u) << 8) | (((x) & 0x000000ffu) << 24))
  38. static __inline __uint32_t
  39. __bswap_32 (__uint32_t __bsx)
  40. {
  41. #if __GNUC_PREREQ (4, 3)
  42. return __builtin_bswap32 (__bsx);
  43. #else
  44. return __bswap_constant_32 (__bsx);
  45. #endif
  46. }
  47. /* Swap bytes in 64-bit value. */
  48. #define __bswap_constant_64(x) \
  49. ((((x) & 0xff00000000000000ull) >> 56) \
  50. | (((x) & 0x00ff000000000000ull) >> 40) \
  51. | (((x) & 0x0000ff0000000000ull) >> 24) \
  52. | (((x) & 0x000000ff00000000ull) >> 8) \
  53. | (((x) & 0x00000000ff000000ull) << 8) \
  54. | (((x) & 0x0000000000ff0000ull) << 24) \
  55. | (((x) & 0x000000000000ff00ull) << 40) \
  56. | (((x) & 0x00000000000000ffull) << 56))
  57. __extension__ static __inline __uint64_t
  58. __bswap_64 (__uint64_t __bsx)
  59. {
  60. #if __GNUC_PREREQ (4, 3)
  61. return __builtin_bswap64 (__bsx);
  62. #else
  63. return __bswap_constant_64 (__bsx);
  64. #endif
  65. }
  66. #endif /* _BITS_BYTESWAP_H */