byteswap.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Macros to swap the order of bytes in integer values.
  2. Copyright (C) 1997, 1998 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. */
  20. #ifdef __GNUC__
  21. # define __bswap_16(x) \
  22. (__extension__ \
  23. ({ unsigned short int __bsx = (x); \
  24. ((((__bsx) >> 8) & 0xff) | (((__bsx) & 0xff) << 8)); }))
  25. #else
  26. static __inline unsigned short int
  27. __bswap_16 (unsigned short int __bsx)
  28. {
  29. return ((((__bsx) >> 8) & 0xff) | (((__bsx) & 0xff) << 8));
  30. }
  31. #endif
  32. /* Swap bytes in 32 bit value. */
  33. #ifdef __GNUC__
  34. # define __bswap_32(x) \
  35. (__extension__ \
  36. ({ unsigned int __bsx = (x); \
  37. ((((__bsx) & 0xff000000) >> 24) | (((__bsx) & 0x00ff0000) >> 8) | \
  38. (((__bsx) & 0x0000ff00) << 8) | (((__bsx) & 0x000000ff) << 24)); }))
  39. #else
  40. static __inline unsigned int
  41. __bswap_32 (unsigned int __bsx)
  42. {
  43. return ((((__bsx) & 0xff000000) >> 24) | (((__bsx) & 0x00ff0000) >> 8) |
  44. (((__bsx) & 0x0000ff00) << 8) | (((__bsx) & 0x000000ff) << 24));
  45. }
  46. #endif
  47. #if defined __GNUC__ && __GNUC__ >= 2
  48. /* Swap bytes in 64 bit value. */
  49. # define __bswap_64(x) \
  50. (__extension__ \
  51. ({ union { unsigned long long int __ll; \
  52. unsigned long int __l[2]; } __v, __r; \
  53. __v.__ll = (x); \
  54. __r.__l[0] = __bswap_32 (__v.__l[1]); \
  55. __r.__l[1] = __bswap_32 (__v.__l[0]); \
  56. __r.__ll; }))
  57. #endif