Add two integers using only bitwise operators?

后端 未结 7 1267
遇见更好的自我
遇见更好的自我 2020-11-27 12:41

In C#, is it possible to perform a sum of two 32-bit integers without using things like if..else, loops etc?

That is, can it be done using only the bitwise operation

7条回答
  •  囚心锁ツ
    2020-11-27 13:26

            int  b =  25;
            for (int t = 128; t > 0; t = t / 2)
            {
                if ((b & t) != 0) Console.Write("1 ");
                if ((b & t) == 0) Console.Write("0 ");
            }
            Console.WriteLine();
            //b = (sbyte)~b;
            int e = 22;
            for (int t = 128; t > 0; t = t / 2)
            {
                if ((e & t) != 0) Console.Write("1 ");
                if ((e & t) == 0) Console.Write("0 ");
            }
            Console.WriteLine();
            int c = b | e;
            for (int t = 128; t > 0; t = t / 2)
            {
                if ((c & t) != 0) Console.Write("1 ");
                if ((c & t) == 0) Console.Write("0 ");
            }
    

提交回复
热议问题