且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

除了为二进制运算

更新时间:2023-11-08 22:19:22

您不能执行除了简单的布尔运算符,你需要一个加法器。 (当然,加法器可以使用一些更复杂的布尔运算符来构建。)
加法器将两个位加随身携带,并通过开展到下一位。

You can not perform addition with simple boolean operators, you need an adder. (Of course the adder can be built using some more complex boolean operators.) The adder adds two bits plus carry, and passes carry out to next bit.

伪code:

carry = 0
for i = 31 to 0
  sum = a[i] + b[i] + carry
  result[i] = sum & 1
  carry = sum >> 1
next i

下面是一个使用VEDIT文本编辑器的宏语言的实现。
要添加的两个数字给定为ASCII字符串,每行一个。
结果被插入在第三行

Here is an implementation using the macro language of VEDIT text editor. The two numbers to be added are given as ASCII strings, one on each line. The results are inserted on the third line.

Reg_Empty(10)                       // result as ASCII string
#0 = 0                              // carry bit
for (#9=31; #9>=0; #9--) {
    #1 = CC(#9)-'0'                 // a bit from first number
    #2 = CC(#9+34)-'0'              // a bit from second number
    #3 = #0+#1+#2                   // add with carry
    #4 = #3 & 1                     // resulting bit
    #0 = #3 >> 1                    // new carry
    Num_Str(#4, 11, LEFT)           // convert bit to ASCII
    Reg_Set(10, @11, INSERT)        // insert bit to start of string
}
Line(2)
Reg_Ins(10) IN
Return

例输入和输出:

00010011011111110101000111100001
00110110111010101100101101110111
01001010011010100001110101011000

编辑:的结果
这里是伪code其中加法器已经实现与布尔操作:


Here is pseudocode where the adder has been implemented with boolean operations:

carry = 0
for i = 31 to 0
  sum[i] = a[i] ^ b[i] ^ carry
  carry = (a[i] & b[i]) | (a[i] & carry) | (b[i] & carry)
next i