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.

101 lines
1.9 KiB

  1. /* Copyright (C) 2001-2017 Peter Selinger.
  2. * This file is part of Potrace. It is free software and it is covered
  3. * by the GNU General Public License. See the file COPYING for details. */
  4. /* bits.h: this file defines some macros for bit manipulations. We
  5. * provide a generic implementation, as well as machine- and
  6. * compiler-specific fast implementations */
  7. /* lobit: return the position of the rightmost "1" bit of an int, or
  8. * 32 if none. hibit: return 1 + the position of the leftmost "1" bit
  9. * of an int, or 0 if none. Note: these functions work on 32-bit
  10. * integers. */
  11. #ifndef BITOPS_H
  12. #define BITOPS_H
  13. #ifdef HAVE_CONFIG_H
  14. #include <config.h>
  15. #endif
  16. /* ---------------------------------------------------------------------- */
  17. /* machine specific macros */
  18. #if defined( HAVE_I386 )
  19. static inline unsigned int lobit( unsigned int x )
  20. {
  21. unsigned int res;
  22. asm ( "bsf %1,%0\n\t"
  23. "jnz 0f\n\t"
  24. "movl $32,%0\n"
  25. "0:"
  26. : "=r" ( res )
  27. : "r" ( x )
  28. : "cc" );
  29. return res;
  30. }
  31. static inline unsigned int hibit( unsigned int x )
  32. {
  33. unsigned int res;
  34. asm ( "bsr %1,%0\n\t"
  35. "jnz 0f\n\t"
  36. "movl $-1,%0\n"
  37. "0:"
  38. : "=r" ( res )
  39. : "r" ( x )
  40. : "cc" );
  41. return res + 1;
  42. }
  43. /* ---------------------------------------------------------------------- */
  44. #else /* generic macros */
  45. static inline unsigned int lobit( unsigned int x )
  46. {
  47. unsigned int res = 32;
  48. while( x & 0xffffff )
  49. {
  50. x <<= 8;
  51. res -= 8;
  52. }
  53. while( x )
  54. {
  55. x <<= 1;
  56. res -= 1;
  57. }
  58. return res;
  59. }
  60. static inline unsigned int hibit( unsigned int x )
  61. {
  62. unsigned int res = 0;
  63. while( x > 0xff )
  64. {
  65. x >>= 8;
  66. res += 8;
  67. }
  68. while( x )
  69. {
  70. x >>= 1;
  71. res += 1;
  72. }
  73. return res;
  74. }
  75. #endif
  76. #endif /* BITOPS_H */