count_zeros.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* SPDX-License-Identifier: GPL-2.0-or-later */
  2. /* Count leading and trailing zeros functions
  3. *
  4. * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
  5. * Written by David Howells (dhowells@redhat.com)
  6. */
  7. #ifndef _LINUX_BITOPS_COUNT_ZEROS_H_
  8. #define _LINUX_BITOPS_COUNT_ZEROS_H_
  9. #include <asm/bitops.h>
  10. /**
  11. * count_leading_zeros - Count the number of zeros from the MSB back
  12. * @x: The value
  13. *
  14. * Count the number of leading zeros from the MSB going towards the LSB in @x.
  15. *
  16. * If the MSB of @x is set, the result is 0.
  17. * If only the LSB of @x is set, then the result is BITS_PER_LONG-1.
  18. * If @x is 0 then the result is COUNT_LEADING_ZEROS_0.
  19. */
  20. static inline int count_leading_zeros(unsigned long x)
  21. {
  22. if (sizeof(x) == 4)
  23. return BITS_PER_LONG - fls(x);
  24. else
  25. return BITS_PER_LONG - fls64(x);
  26. }
  27. #define COUNT_LEADING_ZEROS_0 BITS_PER_LONG
  28. /**
  29. * count_trailing_zeros - Count the number of zeros from the LSB forwards
  30. * @x: The value
  31. *
  32. * Count the number of trailing zeros from the LSB going towards the MSB in @x.
  33. *
  34. * If the LSB of @x is set, the result is 0.
  35. * If only the MSB of @x is set, then the result is BITS_PER_LONG-1.
  36. * If @x is 0 then the result is COUNT_TRAILING_ZEROS_0.
  37. */
  38. static inline int count_trailing_zeros(unsigned long x)
  39. {
  40. #define COUNT_TRAILING_ZEROS_0 (-1)
  41. if (sizeof(x) == 4)
  42. return ffs(x);
  43. else
  44. return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
  45. }
  46. #endif /* _LINUX_BITOPS_COUNT_ZEROS_H_ */