byteswap.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (C) 2005 Atmel Corporation
  3. *
  4. * This file is subject to the terms and conditions of the GNU Lesser General
  5. * Public License. See the file "COPYING.LIB" in the main directory of this
  6. * archive for more details.
  7. */
  8. #if !defined _BYTESWAP_H && !defined _NETINET_IN_H
  9. # error "Never use <bits/byteswap.h> directly; include <byteswap.h> instead."
  10. #endif
  11. #ifndef _BITS_BYTESWAP_H
  12. #define _BITS_BYTESWAP_H 1
  13. /* Swap bytes in 16 bit value. */
  14. #if defined __GNUC__
  15. # define __bswap_16(x) (__extension__ __builtin_bswap_16(x))
  16. #else
  17. /* This is better than nothing. */
  18. static __inline__ unsigned short int
  19. __bswap_16 (unsigned short int __bsx)
  20. {
  21. return ((((__bsx) >> 8) & 0xff) | (((__bsx) & 0xff) << 8));
  22. }
  23. #endif
  24. /* Swap bytes in 32 bit value. */
  25. #if defined __GNUC__
  26. # define __bswap_32(x) (__extension__ __builtin_bswap_32(x))
  27. #else
  28. static __inline__ unsigned int
  29. __bswap_32 (unsigned int __bsx)
  30. {
  31. return ((((__bsx) & 0xff000000) >> 24) | (((__bsx) & 0x00ff0000) >> 8) |
  32. (((__bsx) & 0x0000ff00) << 8) | (((__bsx) & 0x000000ff) << 24));
  33. }
  34. #endif
  35. #if defined __GNUC__
  36. /* Swap bytes in 64 bit value. */
  37. # define __bswap_constant_64(x) \
  38. ((((x) & 0xff00000000000000ull) >> 56) \
  39. | (((x) & 0x00ff000000000000ull) >> 40) \
  40. | (((x) & 0x0000ff0000000000ull) >> 24) \
  41. | (((x) & 0x000000ff00000000ull) >> 8) \
  42. | (((x) & 0x00000000ff000000ull) << 8) \
  43. | (((x) & 0x0000000000ff0000ull) << 24) \
  44. | (((x) & 0x000000000000ff00ull) << 40) \
  45. | (((x) & 0x00000000000000ffull) << 56))
  46. # define __bswap_64(x) \
  47. (__extension__ \
  48. ({ \
  49. union { \
  50. __extension__ unsigned long long int __ll; \
  51. unsigned int __l[2]; \
  52. } __w, __r; \
  53. if (__builtin_constant_p(x)) \
  54. __r.__ll = __bswap_constant_64(x); \
  55. else { \
  56. __w.__ll = (x); \
  57. __r.__l[0] = __bswap_32(__w.__l[1]); \
  58. __r.__l[1] = __bswap_32(__w.__l[0]); \
  59. } \
  60. __r.__ll; \
  61. }))
  62. #endif
  63. #endif /* _BITS_BYTESWAP_H */