Replace the naive "for" loop in determining power of two with a clever
bitwise solution. This code is around the Internet already and is in
Public Domain.
/* We still may want to use the table if numecs
* is a power of 2.
*/
- int power_of_two;
-
- for (power_of_two = 1; power_of_two <= csize;
- power_of_two *= 2)
- if (numecs == power_of_two) {
- use_NUL_table = true;
- break;
- }
+ if (numecs <= csize && is_power_of_2(numecs)) {
+ use_NUL_table = true;
+ }
}
if (use_NUL_table)
#define ABS(x) ((x) < 0 ? -(x) : (x))
#endif
+/* Whether an integer is a power of two */
+#define is_power_of_2(n) ((n) > 0 && ((n) & ((n) - 1)) == 0)
#define unspecified -1