byteswap.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef _BITS_BYTESWAP_H
  2. #define _BITS_BYTESWAP_H 1
  3. #define ___swab16(x) \
  4. ({ \
  5. unsigned short __x = (x); \
  6. ((unsigned short)( \
  7. (((unsigned short)(__x) & (unsigned short)0x00ffU) << 8) | \
  8. (((unsigned short)(__x) & (unsigned short)0xff00U) >> 8) )); \
  9. })
  10. #define ___swab32(x) \
  11. ({ \
  12. unsigned long __x = (x); \
  13. ((unsigned long)( \
  14. (((unsigned long)(__x) & (unsigned long)0x000000ffUL) << 24) | \
  15. (((unsigned long)(__x) & (unsigned long)0x0000ff00UL) << 8) | \
  16. (((unsigned long)(__x) & (unsigned long)0x00ff0000UL) >> 8) | \
  17. (((unsigned long)(__x) & (unsigned long)0xff000000UL) >> 24) )); \
  18. })
  19. /* these are CRIS specific */
  20. static inline unsigned short __fswab16(unsigned short x)
  21. {
  22. __asm__ ("swapb %0" : "=r" (x) : "0" (x));
  23. return(x);
  24. }
  25. static inline unsigned long __fswab32(unsigned long x)
  26. {
  27. __asm__ ("swapwb %0" : "=r" (x) : "0" (x));
  28. return(x);
  29. }
  30. # define __bswap_16(x) \
  31. (__builtin_constant_p((unsigned short)(x)) ? \
  32. ___swab16((x)) : \
  33. __fswab16((x)))
  34. # define __bswap_32(x) \
  35. (__builtin_constant_p((unsigned long)(x)) ? \
  36. ___swab32((x)) : \
  37. __fswab32((x)))
  38. #if defined __GNUC__ && __GNUC__ >= 2
  39. /* Swap bytes in 64 bit value. */
  40. # define __bswap_constant_64(x) \
  41. ((((x) & 0xff00000000000000ull) >> 56) \
  42. | (((x) & 0x00ff000000000000ull) >> 40) \
  43. | (((x) & 0x0000ff0000000000ull) >> 24) \
  44. | (((x) & 0x000000ff00000000ull) >> 8) \
  45. | (((x) & 0x00000000ff000000ull) << 8) \
  46. | (((x) & 0x0000000000ff0000ull) << 24) \
  47. | (((x) & 0x000000000000ff00ull) << 40) \
  48. | (((x) & 0x00000000000000ffull) << 56))
  49. # define __bswap_64(x) \
  50. (__extension__ \
  51. ({ union { __extension__ unsigned long long int __ll; \
  52. unsigned int __l[2]; } __w, __r; \
  53. if (__builtin_constant_p (x)) \
  54. __r.__ll = __bswap_constant_64 (x); \
  55. else \
  56. { \
  57. __w.__ll = (x); \
  58. __r.__l[0] = __bswap_32 (__w.__l[1]); \
  59. __r.__l[1] = __bswap_32 (__w.__l[0]); \
  60. } \
  61. __r.__ll; }))
  62. #endif
  63. #endif /* _BITS_BYTESWAP_H */