You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.1KB

  1. #ifndef __BSWAP_H__
  2. #define __BSWAP_H__
  3. #ifdef HAVE_CONFIG_H
  4. #include "config.h"
  5. #endif
  6. #ifdef HAVE_BYTESWAP_H
  7. #include <byteswap.h>
  8. #else
  9. #include <inttypes.h>
  10. #ifdef ARCH_X86
  11. inline static unsigned short ByteSwap16(unsigned short x)
  12. {
  13. __asm("xchgb %b0,%h0" :
  14. "=q" (x) :
  15. "0" (x));
  16. return x;
  17. }
  18. #define bswap_16(x) ByteSwap16(x)
  19. inline static unsigned int ByteSwap32(unsigned int x)
  20. {
  21. #if __CPU__ > 386
  22. __asm("bswap %0":
  23. "=r" (x) :
  24. #else
  25. __asm("xchgb %b0,%h0\n"
  26. " rorl $16,%0\n"
  27. " xchgb %b0,%h0":
  28. "=q" (x) :
  29. #endif
  30. "0" (x));
  31. return x;
  32. }
  33. #define bswap_32(x) ByteSwap32(x)
  34. inline static unsigned long long int ByteSwap64(unsigned long long int x)
  35. {
  36. register union { __extension__ unsigned long long int __ll;
  37. unsigned long int __l[2]; } __x;
  38. asm("xchgl %0,%1":
  39. "=r"(__x.__l[0]),"=r"(__x.__l[1]):
  40. "0"(bswap_32((unsigned long)x)),"1"(bswap_32((unsigned long)(x>>32))));
  41. return __x.__ll;
  42. }
  43. #define bswap_64(x) ByteSwap64(x)
  44. #else
  45. #define bswap_16(x) (((x) & 0x00ff) << 8 | ((x) & 0xff00) >> 8)
  46. // code from bits/byteswap.h (C) 1997, 1998 Free Software Foundation, Inc.
  47. #define bswap_32(x) \
  48. ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
  49. (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
  50. #define bswap_64(x) \
  51. (__extension__ \
  52. ({ union { __extension__ unsigned long long int __ll; \
  53. unsigned long int __l[2]; } __w, __r; \
  54. __w.__ll = (x); \
  55. __r.__l[0] = bswap_32 (__w.__l[1]); \
  56. __r.__l[1] = bswap_32 (__w.__l[0]); \
  57. __r.__ll; }))
  58. #endif /* !ARCH_X86 */
  59. #endif /* !HAVE_BYTESWAP_H */
  60. // be2me ... BigEndian to MachineEndian
  61. // le2me ... LittleEndian to MachineEndian
  62. #ifdef WORDS_BIGENDIAN
  63. #define be2me_16(x) (x)
  64. #define be2me_32(x) (x)
  65. #define be2me_64(x) (x)
  66. #define le2me_16(x) bswap_16(x)
  67. #define le2me_32(x) bswap_32(x)
  68. #define le2me_64(x) bswap_64(x)
  69. #else
  70. #define be2me_16(x) bswap_16(x)
  71. #define be2me_32(x) bswap_32(x)
  72. #define be2me_64(x) bswap_64(x)
  73. #define le2me_16(x) (x)
  74. #define le2me_32(x) (x)
  75. #define le2me_64(x) (x)
  76. #endif
  77. #endif