ffs.c 874 B

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