return ((x != 0) && !(x & (x - 1))); This is beautiful.
static INLINE boolean
util_is_power_of_two( unsigned v )
{
return (v & (v-1)) == 0;
}41–50 of 82 posts
return ((x != 0) && !(x & (x - 1))); This is beautiful.
static INLINE boolean
util_is_power_of_two( unsigned v )
{
return (v & (v-1)) == 0;
}It seems bizarre to call the first group of methods "decimal based" when the methods don't ever look at the decimal digits of the number being tested. I would call them "arithmetic" or something like that.
Earlier quoted context omitted.
And 3 == 2^(log_2(3)). Clearly we want to know if x is an integer power of 2.
2^(bitsize) == 0. Edit: Yes, 1 << bitsize is undefined. But unsigned integers actually do have well-defined semantics on overflow, and multiplying by 2 enough times really does produce zero.
Earlier quoted context omitted.
And 3 == 2^(log_2(3)). Clearly we want to know if x is an integer power of 2.
2^(bitsize) == 0. Edit: Yes, 1 << bitsize is undefined. But unsigned integers actually do have well-defined semantics on overflow, and multiplying by 2 enough times really does produce zero.
If you meant 1 << (bitsize), that's undefined behaviour in C
Creating a 2GiB lookup table is ~10% faster on my machine than method #10. That is, faster on the benchmark in the blog post. A 2GiB lookup table is horrible, has a little setup cost dominated by calloc-ing the array, and would trash caches with real code.
A also made a solution using a union to split x into two shorts and a 64kiB lookup table that was ~15% slower. For more expensive functions, lookup tables are an annoying baseline to beat. (Although still often good to avoid because of dealing with setup, cache problems, etc.)
[deleted]
return ((x != 0) && !(x & (x - 1))); This is beautiful.
And fast; Mesa uses this. static INLINE boolean util_is_power_of_two( unsigned v ) { return (v & (v-1)) == 0; }
Further, this technique - correctly applied - is essentially #9 in the list.
Is there a reason this won't work? It's the most 'readable' way I could come up with. #(python code) def is_power_of_two(n): import math if n
That was Java and your example is in Python, there could be some difference. If you try and compare in Python, please tell us the result.