1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /* Count leading and trailing zeros functions
4 * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
8 #ifndef _LINUX_BITOPS_COUNT_ZEROS_H_
9 #define _LINUX_BITOPS_COUNT_ZEROS_H_
11 #include <asm/bitops.h>
14 * count_leading_zeros - Count the number of zeros from the MSB back
17 * Count the number of leading zeros from the MSB going towards the LSB in @x.
19 * If the MSB of @x is set, the result is 0.
20 * If only the LSB of @x is set, then the result is BITS_PER_LONG-1.
21 * If @x is 0 then the result is COUNT_LEADING_ZEROS_0.
23 static inline int count_leading_zeros(unsigned long x)
26 return BITS_PER_LONG - fls(x);
28 return BITS_PER_LONG - fls64(x);
31 #define COUNT_LEADING_ZEROS_0 BITS_PER_LONG
34 * count_trailing_zeros - Count the number of zeros from the LSB forwards
37 * Count the number of trailing zeros from the LSB going towards the MSB in @x.
39 * If the LSB of @x is set, the result is 0.
40 * If only the MSB of @x is set, then the result is BITS_PER_LONG-1.
41 * If @x is 0 then the result is COUNT_TRAILING_ZEROS_0.
43 static inline int count_trailing_zeros(unsigned long x)
45 #define COUNT_TRAILING_ZEROS_0 (-1)
50 return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
53 #endif /* _LINUX_BITOPS_COUNT_ZEROS_H_ */