linux/include/linux/count_zeros.h
<<
>>
Prefs
   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
   8#ifndef _LINUX_BITOPS_COUNT_ZEROS_H_
   9#define _LINUX_BITOPS_COUNT_ZEROS_H_
  10
  11#include <asm/bitops.h>
  12
  13/**
  14 * count_leading_zeros - Count the number of zeros from the MSB back
  15 * @x: The value
  16 *
  17 * Count the number of leading zeros from the MSB going towards the LSB in @x.
  18 *
  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.
  22 */
  23static inline int count_leading_zeros(unsigned long x)
  24{
  25        if (sizeof(x) == 4)
  26                return BITS_PER_LONG - fls(x);
  27        else
  28                return BITS_PER_LONG - fls64(x);
  29}
  30
  31#define COUNT_LEADING_ZEROS_0 BITS_PER_LONG
  32
  33/**
  34 * count_trailing_zeros - Count the number of zeros from the LSB forwards
  35 * @x: The value
  36 *
  37 * Count the number of trailing zeros from the LSB going towards the MSB in @x.
  38 *
  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.
  42 */
  43static inline int count_trailing_zeros(unsigned long x)
  44{
  45#define COUNT_TRAILING_ZEROS_0 (-1)
  46
  47        if (sizeof(x) == 4)
  48                return ffs(x);
  49        else
  50                return (x != 0) ? __ffs(x) : COUNT_TRAILING_ZEROS_0;
  51}
  52
  53#endif /* _LINUX_BITOPS_COUNT_ZEROS_H_ */
  54