Skip to contentSkip to conversation

more possible aesthetic cleanup -- *lots* of power of 2 stuff

DISCUSSION Robert P. J. Day 1 participant 1 message Nov 10, 2010

lore
Share & tools
lore
#0 lore raw

following up on jesper's yeoman efforts to tidy up a lot of the
*malloc calls, once upon a time, i whined enough to get the <linux/log2.h> header file added so that a lot of painful bit tests for power of 2 could be abbreviated.

the most useful test seems to have been:

static inline __attribute__((const))
bool is_power_of_2(unsigned long n)

{
        return (n != 0 && ((n & (n - 1)) == 0));
}

i wrote a short script that looks for various forms of the old power of 2 tests:

===== start =====
#!/bin/sh

DIR=${1-*}

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

and, unsurprisingly, while i once submitted a fair bit of that cleanup, there's lots left -- just run the script at the top of the source tree (give an optional subdir to restrict the search). there are even a few places where code is still defining that test for itself:

drivers/net/bna/bna.h:50:#define BNA_POWER_OF_2(x) (((x) & ((x) - 1)) == 0)
drivers/net/wireless/rt2x00/rt2x00reg.h:187:#define is_power_of_two(x) ( !((x) & ((x)-1)) )

if anyone wants to run the script on their favourite bit of the
tree, have at it.

rday

p.s. perhaps tests like this could be added to the checkpatch.pl script. just a thought.

Signature · 7 lines
========================================================================
Robert P. J. Day                               Waterloo, Ontario, CANADA
                        http://crashcourse.ca

Twitter:                                       http://twitter.com/rpjday
LinkedIn:                               http://ca.linkedin.com/in/rpjday
========================================================================