Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

One they missed: (x & -x) == x


That was #9:

    int isPowerOfTwo (unsigned int x)
    {
      return ((x != 0) && !(x & (x - 1)));
    }


This works for negative values of x, though.

It should be: ((x>0) && ((x & -x) == x))


This is method 10 in the article, since -x is equivalent to ~x+1.


Unfortunately this doesn't work for x=0.


2^-infinity == 0


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.


Actually, it's undefined behaviour. http://blog.regehr.org/archives/213


2^(bitsize) == 2^(bitsize)

If you meant 1 << (bitsize), that's undefined behaviour in C


So make it x && blah. Do I really have to state the obvious?


You're a computer programmer (probably). Yes you have to state the obvious...




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: