adding one to a number using only bit operations

This topic is 4304 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I've been trying to brush up on my bit math skills and I ran into an interesting practice excercise. Would anyone know how to add 1 to a number without using the + or - operators and using only bitwise operations? I ended up writing this multiple-line/slow/intuitive algorithm but is there like a some fancy/fast/unintuitive trick to doing it in one line. Thanks,

Share on other sites
Binary digit addition (as any other addition, too) could produce an overflow that has to be propagated to the next higher digit. So a digit shows an inherent dependency on all lower digits. That can be solved either by an iterative process or else a growing look-ahead functionality (or else a combination of those).

Since you're adding 1 only, the propagation is to be done as long as the current digit of the number is 1. E.g.:
int mask = 1;number ^= mask;while(!(number&mask)) number ^= (mask<<=1);

Not a 1-liner yet, sorry :)

(Hopefully I have not done someone's homework ...)

[Edited by - haegarr on April 6, 2006 11:42:54 AM]