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.
unsigned int i = ...;
unsigned int mask = 1;
while (i & mask)
{
i &= ~mask;
mask <<= 1;
}
i |= mask;
Java:
public static int inc(int i){
if ((i & 1) == 0)
return i | 1;
else
return inc(i>>1)<<1;
}
P.S. while loop variant by henrik is obviously faster
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With