Sunday, July 10, 2016

add without plus

a  0011
b  0101
t  0110 //temp
c 01110 //carry
d  1000 //digit
add(a, b):
    sum = 0
    carry = 0
    i = 0
    while a != 0 || b != 0 || carry != 0:
        digit = add(a, b, carry)
        sum |= (digit << i)
        i++
        carry = carry(a, b, carry)
        a = a >>> 1, b = b >>> 1
    return sum

add(b1, b2, b3):
    return (b1 ^ b2 ^ b3) &1
carry(b1, b2, b3):
    return ((b1 & b2) | (b2 & b3) | (b3 & b1)) &1
Better way is this.
 11 a
  1 b
 10 a^b
 01 a&b
 10 a&b << 1
 
 10 a
 10 b
 00 a^b
 10 a&b
100 a&b << 1

100 a
  0 b
100 a^b
  0 a&b
  0 a&b << 1

100 return
(a, b):
    while b != 0:
        a = a ^ b
        carry = a & b
        b = carry << 1
    return a
[Hat tip to ctci]

No comments:

Post a Comment