Jump to content
  • Advertisement
Sign in to follow this  
axv4745

adding one to a number using only bit operations

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!