ffs.c 829 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. 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)