ffs.c 879 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (C) 2002 Manuel Novoa III
  3. * Copyright (C) 2000-2005 Erik Andersen <andersen@uclibc.org>
  4. *
  5. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  6. */
  7. /* ffsl,ffsll */
  8. #include "_string.h"
  9. /* Experimentally off - libc_hidden_proto(ffs) */
  10. int ffs(int i)
  11. {
  12. #if 1
  13. /* inlined binary search method */
  14. char n = 1;
  15. #if UINT_MAX == 0xffffU
  16. /* nothing to do here -- just trying to avoiding possible problems */
  17. #elif UINT_MAX == 0xffffffffU
  18. if (!(i & 0xffff)) {
  19. n += 16;
  20. i >>= 16;
  21. }
  22. #else
  23. #error ffs needs rewriting!
  24. #endif
  25. if (!(i & 0xff)) {
  26. n += 8;
  27. i >>= 8;
  28. }
  29. if (!(i & 0x0f)) {
  30. n += 4;
  31. i >>= 4;
  32. }
  33. if (!(i & 0x03)) {
  34. n += 2;
  35. i >>= 2;
  36. }
  37. return (i) ? (n + ((i+1) & 0x01)) : 0;
  38. #else
  39. /* linear search -- slow, but small */
  40. int n;
  41. for (n = 0 ; i ; ++n) {
  42. i >>= 1;
  43. }
  44. return n;
  45. #endif
  46. }
  47. libc_hidden_def(ffs)