Bitwise Addition

Hello everyone!! Welcome to flower brackets blog. Today we will be discussing bitwise addition.

Bitwise Addition

 

Basically bitwise operators allow us to manipulate bit values for comparisons in calculation.

Bitwise operators use similar symbols to boolean operators. First we have (&) ampersand which is “AND” and we have pipe ( | ) which is “OR”, we have the carrot (^) which is “XOR” and the tilde (~) which is NOT.

Also Read – Adding Two Integers Without Using Arithmetic Operator

Bitwise addition is common question in java interview. So, let’s see an example on how to add two numbers without using + operator in java.

Example : bitwise addition

//  addition using bitwise operators

import java.util.Scanner;

public class BitwiseAddition
{
   static int add(int a,int b)
   {
      int carry;  // declare integer carry variable

      while(b != 0)
      {
         carry = a & b;
         a = a ^ b;
         b = carry << 1;
      }
      return a;
   }

   // The main() method starts here

   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      // scanner which can parse primitive types and strings using regular expressions.

      System.out.println("Please enter numbers to be added: ");

      int a = sc.nextInt();  // Scans the next token of the input as an int

      int b = sc.nextInt();  // Scans the next token of the input as an int

      System.out.println("The output is: " + add(a,b));
      sc.close();  // Closes this scanner

   }
}

Output:

Please enter numbers to be added: 5 5
The output is: 10


Bitwise subtraction

Here let’s learn subtraction using bitwise operators or java subtraction with an example,

public class BitwiseSubtraction 
{
   static int bitSubtraction(int a, int b)
   {
      while(b != 0)
      { 
         int subtract = (~a) & b; 
         a = a ^ b; 
         b = subtract << 1;
      } 
      return a;
   }

   public static void main(String[] args) 
   {
      int m = 70, n = 50; 
      System.out.println("Bitwise subtraction of m - n is " + bitSubtraction(m, n));
   }
}

Output:

Bitwise subtraction of m – n is 20


conclusion

That’s it guys. This is all about add two numbers without using + operator. I hope you have understood bitwise addition.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

You May Also Like