I got into a discussion with a fellow student today who worked at Microsoft. His product manager told him not to use bit operations because it’s important to keep code readable. Code should be self-documenting. I agree with this, but when you can perform functions with a couple lines of bit operations, it can be a beautiful thing.
Here’s how to determine if a number is a power of two:
1 | (n & (n - 1)) == 0 |
Of course, this sets 0 to be a power of two as well. I found this site which recommends using this instead which fixes this.
1 | v && !(v & (v - 1)) |