Advertisements
adding two integer numbers with using bitwise opeators
Hi Friend,
Try the following code:
public class AddNumberUsingBitwiseOperators { public static void main(String[] args) { System.out.println("Adding 5 and 6......"); int x=5,y=6; int xor, and, temp; and = x & y; xor = x ^ y; while(and != 0 ) { and <<= 1; temp = xor ^ and; and &= xor; xor = temp; } System.out.println(xor); } }
Thanks
*hi friends , my name is Rajasekhar kadiveti "43857" the above program has one error,so remove that line i.e is*
and &=xor; the above can be written in simple format .
Logic:
int X,Y; int Z=(((X&Y)<<1)^(X^Y)); System.out.println(Z);
OR
class Sum { public static viod main(String args[]) { int X,Y,A,B; X=3; y=4; A=X&Y; B=X^Y; A=A<<1; int Z=A^B; System.out.println("sum="+Z);
}
}
out put: step by step
X=0000 0011
Y=0000 0100
A=0000 0000 (X&Y)
B=0000 0111 (X^Y)
A=0000 0000 (A<<1)
Z=0000 0111 (A^B)
Z=7.
Eg:
x = 10, y = 20, z = 0; z = ( (x&y) << 1 ) | (x^y);