In C++ I routinely use this templated function...
template<typename T>
bool isPowerOf2 (T x) // returns nonzero if x is a power-of-2
{
return x && ((x & (~x + 1)) == x);
}
...and I'm trying to implement the same thing in C#. So here's the best I can come up with:
public class Utils
{
// ...
public static bool isPowerOf2<T>(T x) // returns true if x is a power-of-2
{
return (x != 0) && ((x & (~x + 1)) == x);
}
}
But Visual Studio complains that error CS0019: Operator '!=' cannot be applied to operands of type 'T' and 'int'
and error CS0023: Operator '~' cannot be applied to operand of type 'T'
.
If I remove the generic stuff & just make it "public static bool isPowerOf2(int x)
", it works fine (just like in various implementations here), but I'd like the implementation to be generic so it would work on any integer type.