Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0-or-later */
0002 /* Count leading and trailing zeros functions
0003  *
0004  * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
0005  * Written by David Howells (dhowells@redhat.com)
0006  */
0007 
0008 #ifndef _LINUX_BITOPS_COUNT_ZEROS_H_
0009 #define _LINUX_BITOPS_COUNT_ZEROS_H_
0010 
0011 #include <asm/bitops.h>
0012 
0013 /**
0014  * count_leading_zeros - Count the number of zeros from the MSB back
0015  * @x: The value
0016  *
0017  * Count the number of leading zeros from the MSB going towards the LSB in @x.
0018  *
0019  * If the MSB of @x is set, the result is 0.
0020  * If only the LSB of @x is set, then the result is BITS_PER_LONG-1.
0021  * If @x is 0 then the result is COUNT_LEADING_ZEROS_0.
0022  */
0023 static inline int count_leading_zeros(unsigned long x)
0024 {
0025     if (sizeof(x) == 4)
0026         return BITS_PER_LONG - fls(x);
0027     else
0028         return BITS_PER_LONG - fls64(x);
0029 }
0030 
0031 #define COUNT_LEADING_ZEROS_0 BITS_PER_LONG
0032 
0033 /**
0034  * count_trailing_zeros - Count the number of zeros from the LSB forwards
0035  * @x: The value
0036  *
0037  * Count the number of trailing zeros from the LSB going towards the MSB in @x.
0038  *
0039  * If the LSB of @x is set, the result is 0.
0040  * If only the MSB of @x is set, then the result is BITS_PER_LONG-1.
0041  * If @x is 0 then the result is COUNT_TRAILING_ZEROS_0.
0042  */
0043 static inline int count_trailing_zeros(unsigned long x)
0044 {
0045 #define COUNT_TRAILING_ZEROS_0 (-1)
0046 
0047     if (sizeof(x) == 4)
0048         return ffs(x);
0049     else
0050         return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
0051 }
0052 
0053 #endif /* _LINUX_BITOPS_COUNT_ZEROS_H_ */