count_zeros.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Count leading and trailing zeros functions
  2. *
  3. * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
  4. * Written by David Howells (dhowells@redhat.com)
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public Licence
  8. * as published by the Free Software Foundation; either version
  9. * 2 of the Licence, or (at your option) any later version.
  10. */
  11. #ifndef _LINUX_BITOPS_COUNT_ZEROS_H_
  12. #define _LINUX_BITOPS_COUNT_ZEROS_H_
  13. #include <asm/bitops.h>
  14. /**
  15. * count_leading_zeros - Count the number of zeros from the MSB back
  16. * @x: The value
  17. *
  18. * Count the number of leading zeros from the MSB going towards the LSB in @x.
  19. *
  20. * If the MSB of @x is set, the result is 0.
  21. * If only the LSB of @x is set, then the result is BITS_PER_LONG-1.
  22. * If @x is 0 then the result is COUNT_LEADING_ZEROS_0.
  23. */
  24. static inline int count_leading_zeros(unsigned long x)
  25. {
  26. if (sizeof(x) == 4)
  27. return BITS_PER_LONG - fls(x);
  28. else
  29. return BITS_PER_LONG - fls64(x);
  30. }
  31. #define COUNT_LEADING_ZEROS_0 BITS_PER_LONG
  32. /**
  33. * count_trailing_zeros - Count the number of zeros from the LSB forwards
  34. * @x: The value
  35. *
  36. * Count the number of trailing zeros from the LSB going towards the MSB in @x.
  37. *
  38. * If the LSB of @x is set, the result is 0.
  39. * If only the MSB of @x is set, then the result is BITS_PER_LONG-1.
  40. * If @x is 0 then the result is COUNT_TRAILING_ZEROS_0.
  41. */
  42. static inline int count_trailing_zeros(unsigned long x)
  43. {
  44. #define COUNT_TRAILING_ZEROS_0 (-1)
  45. if (sizeof(x) == 4)
  46. return ffs(x);
  47. else
  48. return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
  49. }
  50. #endif /* _LINUX_BITOPS_COUNT_ZEROS_H_ */