-4

What does the function result return in the code below?

unsigned int result(unsigned int number) {
   return number & (number - 1);
}
Jim Balter
  • 16,163
  • 3
  • 43
  • 66
Lentan
  • 13
  • 4

2 Answers2

4

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.

harold
  • 61,398
  • 6
  • 86
  • 164
  • there is also an implicit cast ... – user2485710 Dec 06 '13 at 16:47
  • if you perform a math operation between an unsigned and a signed you get a signed value, the expected return value is also an unsigned, so there are probably 2 casts. – user2485710 Dec 06 '13 at 16:49
  • @user2485710 ok, but that doesn't change anything does it? – harold Dec 06 '13 at 16:52
  • just my 2 cent, I love to be pedantic, especially with C :D – user2485710 Dec 06 '13 at 16:52
  • Good answer - but one of those times when you have to hesitate between "oh, I know this!" and "hey - this is a CS homework question. Do your own thinking, you will learn more". Or even - do your own googling. Just putting "number & (number - 1)" in quotes will find a top hit of http://stackoverflow.com/questions/9598781/how-to-determine-the-number-of-right-bit-shifts-needed-for-a-power-of-two-value , which gets to the answer pretty quickly - or second hit http://www.careercup.com/question?id=8075496 which is even closer. – Floris Dec 06 '13 at 17:06
  • @Floris good point - but couldn't you also argue that since it's so trivial to find anyway, answering it doesn't really make it easier for the OP? – harold Dec 06 '13 at 17:10
  • @harold - this is entirely a matter of (teaching) style. This is a personal choice - there can be no 'right or wrong'. I voiced my opinion. If the purpose of SO is just to provide answers, you did the right thing. If it's to make better programmers out of all of us (I hope so...) then "teach a man to fish". – Floris Dec 06 '13 at 17:23
0

It checks if number is of the form 2^x (or 0) and returns 0 in that case, or != 0 in other cases.

Juri Robl
  • 5,614
  • 2
  • 29
  • 46