Add two numbers using bitwise operators in java

Java program for Add two numbers using bitwise operators. Here problem description and explanation.

// Java program for
// Add two numbers using of bitwise operators
public class NumberAddition
{
	// Add two numbers
	public void addition(int a, int b)
	{
		// Display given numbers
		System.out.print("\n [(" + a + ") + (" + b + ")] ");
		// Auxiliary variable which are store the carry result
		int carry_bit = 0;
		// Executing loop, until b value is not zero
		while (b != 0)
		{
			// Get carry bits of a & b
			carry_bit = a & b;
			// Sum of bits of a ^ b
			a = a ^ b;
			// Shift the carry bit by one bit in left side
			b = carry_bit << 1;
		}
		// Display add result
		System.out.print(" : " + a);
	}
	public static void main(String[] args)
	{
		NumberAddition task = new NumberAddition();
		// Test Case
		task.addition(8, -2);
		task.addition(5, 3);
		task.addition(-3, -5);
	}
}

Output

 [(8) + (-2)]  : 6
 [(5) + (3)]  : 8
 [(-3) + (-5)]  : -8



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved