Java without arithmetic adder

I found code to add two numbers using XOR and AND without using any arithmetic operators.

I understand that x ^ y equals the sum and that x & y equals the carry. However, I do not understand why the transfer should be biased? My knowledge of the left bit shift is the same as multiplying by two. Why is the transfer repeated in two?

public static int add(int x, int y) {

    // Iterate till there is no carry  
    while (y != 0)
    {
        // carry
        int carry = x & y;  

        // Sum 
        x = x ^ y; 


        y = carry << 1;
    }
    return x;

}

Any guidance is appreciated.

+4
source share
1 answer

Let's try with two small integers x = 5, whose binary equivalent is 101 and y = 1, whose binary equivalent is 001.

, , ? XOR - .

, XOR x y, :

x = x ^ y = 101 ^ 001 = 100 (: 4)

, XOR . ( 5 1 6, 4). , . , .

, .

,

carry = x y = 101 001 = 1 ( 1)

y = carry < 1;

, y = 001 < 1 = 010 (: 2)

, y .

( y = 2, )

x = x ^ y = 100 ^ 010 = 110 (: 6)

carry = x y = 100 010 = 0 ( 0)

XOR x y 6, 5 1. , 0.

y 0, 0 0. y , , , x!

+4

All Articles