language-agnosticbit-shift

How to Increment unsigned int by 1 using bit-shifting & logical opr only?


I have a question in my assignment / project that adds 1 to an unsigned integer only using bit-shifting and logical operators. There shouldn't be any "+", "-", "*", or "/" symbols in the function.

I am trying from last days but no success yet. So far I've tried the following:

int A = (((B&C)<<1)^(B^C))

Can anybody help me to solve this.?

You can help me in any programming language.


Solution

  • unsigned int i = ...;
    unsigned int mask = 1;
    while (i & mask)
    {
        i &= ~mask;
        mask <<= 1;
    }
    i |= mask;