【问题标题】:How computer adds two number internally? [duplicate]计算机如何在内部添加两个数字? [复制]
【发布时间】:2016-11-04 21:24:17
【问题描述】:

我相信计算机必须借助按位左移运算符的异或来实现它。对吗?

这是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;
    }

}

【问题讨论】:

  • 你有什么问题?
  • 只是想确认计算机内部采用类似的算法进行添加操作?
  • 计算机在硬件中使用了一系列只能在软件中模拟的门。实际上,加法只需要一个时钟周期即可完成所有操作。

标签: java c algorithm computer-science


【解决方案1】:

我将回答个人计算机、微控制器等中常见的典型位并行处理器。这不适用于bit-serial architecture,它更常见于特定类型的 DSP 等特殊情况和某些 FPGA 设计。

通常情况并非如此,因为对于窄宽度(例如 32 位或 64 位),adder circuit 比您显示的串行加法更有效,因为它可以异步完成加法,而不是多时钟循环。

但是,基本的波纹进位加法器的原理是一样的——最低有效位的加法器计算结果的一位和一个进位位,然后将其传递到下一位对应的全加器中作为进位,等等,如图所示:

来源:Wikimedia Commons,用户 cburnett,在 Creative Commons 3.0 Share-alike 下

然而,实际上,来自 LSB 加法器的进位可能需要一直传播到 MSB 加法器这一事实对性能造成了限制(由于传播延迟),因此可以使用各种先行方案。

【讨论】:

  • 感谢Hexafraction。基本上我只是想确认计算机采用的算法进行加法。正如您所说,它与异步/并行处理等优化类似。
  • @emilly 确实是固定宽度的并行化。与bit-serial architecture比较。
猜你喜欢
  • 2011-03-04
  • 2012-02-17
  • 2011-12-04
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
相关资源
最近更新 更多