byteswap.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Macros to swap the order of bytes in integer values. m68k version.
  2. Copyright (C) 1997 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 Library General Public License as
  6. published by the Free Software Foundation; either version 2 of the
  7. 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. Library General Public License for more details.
  12. You should have received a copy of the GNU Library General Public
  13. License along with the GNU C Library; see the file COPYING.LIB. If not,
  14. write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  15. Boston, MA 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. /* Swap bytes in 16 bit value. We don't provide an assembler version
  20. because GCC is smart enough to generate optimal assembler output, and
  21. this allows for better cse. */
  22. #define __bswap_16(x) \
  23. ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))
  24. /* Swap bytes in 32 bit value. */
  25. #define __bswap_constant_32(x) \
  26. ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
  27. (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
  28. #if defined __GNUC__ && __GNUC__ >= 2
  29. # define __bswap_32(x) \
  30. __extension__ \
  31. ({ unsigned int __v; \
  32. if (__builtin_constant_p (x)) \
  33. __v = __bswap_constant_32 (x); \
  34. else \
  35. __asm__ __volatile__ ("mov.l %0,er0\n\t" \
  36. "mov.b r0l,r1h\n\t" \
  37. "mov.b r0h,r1l\n\t" \
  38. "mov.w r1,e1\n\t" \
  39. "mov.w e0,r0\n\t" \
  40. "mov.b r0l,r1h\n\t" \
  41. "mov.b r0h,r1l\n\t" \
  42. "mov.l er1,%0" \
  43. : "=d" (__v) \
  44. : "0" (x): "er0","er1"); \
  45. __v; })
  46. #else
  47. # define __bswap_32(x) __bswap_constant_32 (x)
  48. #endif
  49. #if defined __GNUC__ && __GNUC__ >= 2
  50. /* Swap bytes in 64 bit value. */
  51. # define __bswap_64(x) \
  52. __extension__ \
  53. ({ union { unsigned long long int __ll; \
  54. unsigned long int __l[2]; } __v, __r; \
  55. __v.__ll = (x); \
  56. __r.__l[0] = __bswap_32 (__v.__l[1]); \
  57. __r.__l[1] = __bswap_32 (__v.__l[0]); \
  58. __r.__ll; })
  59. #endif