除了为二进制运算 [英] Addition as binary operations
问题描述
我添加一对32位无符号二进制整数(包括溢出)的。加法是前pressive而不是实际计算的,所以没有需要一个高效的算法,但由于各组分在单独的位来手工指定,我需要一个具有紧凑重新presentation。有什么建议?
I'm adding a pair of unsigned 32bit binary integers (including overflow). The addition is expressive rather than actually computed, so there's no need for an efficient algorithm, but since each component is manually specified in terms of individual bits, I need one with a compact representation. Any suggestions?
编辑:在布尔运算方面。所以我想, =携带A和b:总和= A ^ B;
为第一位,但其他31
In terms of boolean operators. So I'm thinking that carry = a & b; sum = a ^ b;
for the first bit, but the other 31?
哦,减法!
推荐答案
您不能执行除了简单的布尔运算符,你需要一个加法器。 (当然,加法器可以使用一些更复杂的布尔运算符来构建。)
加法器将两个位加随身携带,并通过开展到下一位。
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
这篇关于除了为二进制运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!