# adding one to a number using only bit operations

This topic is 4632 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]

##### Share on other sites
Any source on beginer digital logic should have a section on this. Its like day three. Your basic logic operations, simplifying logic operations, implementing addition using logic operations. So I'd start there.

CM

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
14
5. 5
frob
12

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633662
• Total Posts
3013231
×