more janitorial work: test for power of 2

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



  i mentioned this before but here's something that can be split over
numerous subsystems so it can be done in bite-size pieces -- testing
if an integer is a power of 2.

  the basic test is simple: do a bitwise "and" between n and n-1, and
if the result is zero, n must be a power of 2 (it is left as an
exercise for the reader to convince themselves of that).  the script i
used years ago was pretty simplistic and tested for different
variations that included parentheses or not (so it's entirely possible
the results are not perfect), but here's the script:

  DIR=${1-*}

  echo "PATTERN:     x & (x - 1):\n"
  grep -Ern "([^\(\)]+) ?\& ?\(\1 ?- ?1\)" ${DIR}
  echo "PATTERN:     x & ((x) - 1):\n"
  grep -Ern "([^\(\)]+) ?\& ?\(\(\1\) ?- ?1\)" ${DIR}
  echo "PATTERN:     (x) & (x - 1):\n"
  grep -Ern "\(([^\(\)]+)\) ?\& ?\(\1 ?- ?1\)" ${DIR}
  echo "PATTERN:     (x) & ((x) - 1):\n"
  grep -Ern "\(([^\(\)]+)\) ?\& ?\(\(\1\) ?- ?1\)" ${DIR}

from the top of the kernel source tree, you can run the script and
pass as the argument the directory you want to scan; for example:

=== start

$ test_for_power_of_2.sh drivers/net/ethernet/mellanox
PATTERN:     x & (x - 1):

drivers/net/ethernet/mellanox/mlx5/core/lib/dm.c:163:	if (!length ||
(length & (length - 1)) ||
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/definer.c:691:
if (flags & (flags - 1))
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/definer.c:697:
if (flags & (flags - 1))
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/definer.c:702:
if (flags & (flags - 1))
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/definer.c:709:
if (flags & (flags - 1))
drivers/net/ethernet/mellanox/mlx5/core/steering/sws/dr_rule.c:680:
byte_mask = byte_mask & (byte_mask - 1);
PATTERN:     x & ((x) - 1):

PATTERN:     (x) & (x - 1):

PATTERN:     (x) & ((x) - 1):

=== end

  you can see the official kernel test for power-of-2 here:

https://github.com/torvalds/linux/blob/master/include/linux/log2.h#L36

so there is a *lot* of kernel code that can be simplified by using
that boolean function.

rday





[Index of Archives]     [Kernel Development]     [Kernel Announce]     [Kernel Newbies]     [Linux Networking Development]     [Share Photos]     [IDE]     [Security]     [Git]     [Netfilter]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Device Mapper]

  Powered by Linux