我相信计算机必须借助按位左移运算符的异或运算来实现它。正确吗?
这是java中的实现
public class TestAddWithoutPlus {
public static void main(String[] args) {
int result = addNumberWithoutPlus(6, 5);
System.out.println("result is " + result);
}
public static int addNumberWithoutPlus(int a, int b) {
if (a == 0) {
return b;
} else if (b == 0) {
return a;
}
int result = 0;
int carry = 0;
while (b != 0) {
result = a^b; // SUM of two bits is A XOR B
carry = (a&b); // CARRY is AND of two bits
carry = carry << 1; // shifts carry to 1 bit to calculate sum
a=result;
b=carry;
}
return result;
}
}
最佳答案
我将回答典型的位并行处理器,如个人计算机、微 Controller 等中所见。这不适用于 bit-serial architecture ,这在特殊情况下更常见,例如某些类型的 DSP 和某些 FPGA 设计。
通常情况并非如此,因为对于 32 或 64 位等窄宽度,adder circuit正如您所展示的,它比串行加法更有效,因为它可以异步完成加法,而不是通过多个时钟周期完成加法。
但是,基本的波纹进位加法器的原理是相同的 - 最低有效位的加法器计算结果的一位和进位位,将其传递到与下一位对应的全加器作为进位等,如下图所示:
来源:Wikimedia Commons ,用户 cburnett,根据知识共享 3.0 相同方式共享
然而,实际上,来自 LSB 加法器的进位可能需要一直传播到 MSB 加法器,这对性能造成了限制(由于传播延迟),因此可以使用各种先行方案。
关于java - 计算机如何在内部将两个数字相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38162794/