What does the function result return in the code below?
unsigned int result(unsigned int number) {
return number & (number - 1);
}
What does the function result return in the code below?
unsigned int result(unsigned int number) {
return number & (number - 1);
}
That's the famous "remove the lowest set bit" trick.
You can find it here (see hack #6), and in The Art of Computer Programming volume 4A, and in Hacker's Delight, among other places.
It works as follows:
Subtracting 1 borrows through all the rightmost zeroes (turning them into ones), and finally resets the lowest one. ANDing with the original number resets the bits that were changed but doesn't change the rest. So the lowest set bit is reset.
It checks if number
is of the form 2^x (or 0) and returns 0 in that case, or != 0 in other cases.