byteswap.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Macros to swap the order of bytes in integer values. m68k version.
  2. Copyright (C) 1997, 2002 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, write to the Free
  14. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA. */
  16. #if !defined _BYTESWAP_H && !defined _NETINET_IN_H
  17. # error "Never use <bits/byteswap.h> directly; include <byteswap.h> instead."
  18. #endif
  19. #ifndef _BITS_BYTESWAP_H
  20. #define _BITS_BYTESWAP_H 1
  21. /* Swap bytes in 16 bit value. We don't provide an assembler version
  22. because GCC is smart enough to generate optimal assembler output, and
  23. this allows for better cse. */
  24. #define __bswap_16(x) \
  25. ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))
  26. /* Swap bytes in 32 bit value. */
  27. #define __bswap_constant_32(x) \
  28. ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
  29. (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
  30. #if defined __GNUC__ && __GNUC__ >= 2
  31. # define __bswap_32(x) \
  32. __extension__ \
  33. ({ unsigned int __bswap_32_v; \
  34. if (__builtin_constant_p (x)) \
  35. __bswap_32_v = __bswap_constant_32 (x); \
  36. else \
  37. __asm__ __volatile__ ("ror%.w %#8, %0;" \
  38. "swap %0;" \
  39. "ror%.w %#8, %0" \
  40. : "=d" (__bswap_32_v) \
  41. : "0" ((unsigned int) (x))); \
  42. __bswap_32_v; })
  43. #else
  44. # define __bswap_32(x) __bswap_constant_32 (x)
  45. #endif
  46. #if defined __GNUC__ && __GNUC__ >= 2
  47. /* Swap bytes in 64 bit value. */
  48. # define __bswap_64(x) \
  49. __extension__ \
  50. ({ union { unsigned long long int __ll; \
  51. unsigned long int __l[2]; } __bswap_64_v, __bswap_64_r; \
  52. __bswap_64_v.__ll = (x); \
  53. __bswap_64_r.__l[0] = __bswap_32 (__bswap_64_v.__l[1]); \
  54. __bswap_64_r.__l[1] = __bswap_32 (__bswap_64_v.__l[0]); \
  55. __bswap_64_r.__ll; })
  56. #endif
  57. #endif /* _BITS_BYTESWAP_H */