This should be easy for C++ people though. But I was asked how to do it in C#. Shouldnt be much of difference.
How to find out if a long variable has only one bit set?
I cant think anything except some brutal force shifting all bits and counting whats set.
A non-negative binary integer value x is a power of 2 if
(x&(x-1))
is 0 using 2's complement arithmetic.
Powers of 2 would mean a single bit is set.
http://aggregate.org/MAGIC/#Is%20Power%20of%202
EDIT:
To allow for the zero case:
bool singleBit = x>0 && (x&(x-1))==0
In C++:
unsigned long v;
bool f; // result
f = v && !(v & (v - 1));
Explanation: v & (v - 1) == 0 if only one bit is set or v == 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With