Re:Ten Ways to Check if an Integer Is a Power Of Two in C
by oldcigarette on Wednesday July 27, 2011 @09:16AM
(#2811960)
gcc should do the right thing if you add a special case for zero. exponent will be negative in that case. For larger integers you might end up with some false positives with floats though for say 2^30+1.
[ Parent
| on HN ]
Re:Ten Ways to Check if an Integer Is a Power Of Two in C
by imurray on Wednesday July 27, 2011 @05:52PM
(#2814359)
Thanks, I had confused myself. You're right: shifting with a negative value (or far too big) gives undefined behaviour in C. (The type punning stuff is formally undefined too, a memcpy would be more portable, but gcc promises to make the widely-used union trick work.)
Regarding the second point, the posted code works fine with 1073741825U (the literal for 2^30+1). The algorithm doesn't need the float to keep full precision, because only the exponent is consulted.