ffs.c 896 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. #include <limits.h>
  8. #include <string.h>
  9. int ffs(int i)
  10. {
  11. #if 1
  12. /* inlined binary search method */
  13. char n = 1;
  14. #if UINT_MAX == 0xffffU
  15. /* nothing to do here -- just trying to avoiding possible problems */
  16. #elif UINT_MAX == 0xffffffffU
  17. if (!(i & 0xffff)) {
  18. n += 16;
  19. i >>= 16;
  20. }
  21. #else
  22. #error ffs needs rewriting!
  23. #endif
  24. if (!(i & 0xff)) {
  25. n += 8;
  26. i >>= 8;
  27. }
  28. if (!(i & 0x0f)) {
  29. n += 4;
  30. i >>= 4;
  31. }
  32. if (!(i & 0x03)) {
  33. n += 2;
  34. i >>= 2;
  35. }
  36. return (i) ? (n + ((i+1) & 0x01)) : 0;
  37. #else
  38. /* linear search -- slow, but small */
  39. int n;
  40. for (n = 0 ; i ; ++n) {
  41. i >>= 1;
  42. }
  43. return n;
  44. #endif
  45. }
  46. libc_hidden_def(ffs)
  47. #if ULONG_MAX == UINT_MAX
  48. strong_alias_untyped(ffs, ffsl)
  49. #endif