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

>y = x & (x-1)

Couldn't you also do: y = x & (~1) ? I'd think that would be slightly more efficient.



These aren't equivalent, though. The example from the linked article turns off the least significant 1 bit in x. Your version turns off the least significant bit in x, regardless of whether it is 1 or 0. They'll give the same result if x ends in a 1 or if x=0, but not in general.


No, that unsets bit #0, not the lowest set bit in x.

Aka. that brings 01101₂→01100₂ correctly, but 01100₂→01100₂ instead of 01100₂→01000₂.


Ah, I completely misunderstood what the author was doing there.




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

Search: