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

前提是你 提交于 2019-12-12 09:05:52

问题


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.


回答1:


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



回答2:


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




回答3:


Logic to inrement a number without using arithmetic operators(+, -. * and /)

unsinged int no = 3; //actual number
unsigned int one = 1;
unsigned int ans = 0;
unsigned int carry = 0;
unsigned int prev_ans = 0;
unsigned int prev_carry = 0;

ans = no ^ one;
carry = no & one;

while (carry != 0)
{
   carry <<= 1;

   prev_ans = ans;
   prev_carry = carry;

   ans = prev_ans ^ prev_carry;
   carry = prev_ans & prev_carry;
}



回答4:


Google for Full Adder and try to implement one.




回答5:


This is too easy, for example in Haskell:

data Unsigned = Zero | Succ Unsigned
increment :: Unsigned -> Unsigned
increment u = Succ u

No bitwise or arithmetic operators, no operators at all!



来源:https://stackoverflow.com/questions/12055240/how-to-increment-unsigned-int-by-1-using-bit-shifting-logical-opr-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!