本文介绍了添加仅使用位运算符两个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,是不是可以不使用像IFS的事情进行两个32位整数的和,别人的,循环等?
In C#, is it possible to perform a sum of two 32-bit integers without using things like ifs, elses, loops etc?
也就是说,它可以只用按位操作或完成,并且,异或,非,左移和右移?
That is, can it be done using only the bitwise operations OR, AND, XOR, NOT, shift left and shift right?
推荐答案下面是您娱乐的例子
unsigned int myAdd(unsigned int a, unsigned int b) { unsigned int carry = a & b; unsigned int result = a ^ b; while(carry != 0) { unsigned int shiftedcarry = carry << 1; carry = result & shiftedcarry; result ^= shiftedcarry; } return result; }循环可以展开。它的执行次数,取决于操作数设置的位数,但它从来没有超过 unsigned int类型的宽度。一旦执行变为 0 ,接下来的迭代不会改变任何东西。
The loop could be unrolled. Number of times it executes, depends on the number of bits set in operands, but it's never greater than the width of unsigned int. Once carry becomes 0, next iterations don't change anything.
更多推荐
添加仅使用位运算符两个整数?
发布评论