Multiplication of 2 integers using bits.

Hi everyone, this post will describe about how to multiply 2 integers using bits. The advantage in multiplying using bits, is it takes less time than simple multiplication.

Consider two numbers 8 and 7, when we are required to multiply both numbers, we will just do like 8 * 7. We can also implement this multiplication using bit shifts. If 8 is the first number and 7 is the second number, we just need to return sum of 8 left shifted four times + 8 left shifted 2 times + 8, i.e, we can return 8<<2 + 8<<1 + 8. Shifting the number one time to left will double the number (When the bit reaches 32nd position, it wont double as it shifts to the 0th position)

For knowing more about bit shifts, please refer my previous post - Bit shifts.

Like this we can multiply an integer with every other integer. Here, I am presenting a few examples.


 public class MultiplyBits {  
      public static void main (String args[])  
      {  
           int num =8;  
           //System.out.println("a = "+ (num<<2));  
           System.out.println(" 8 * 7 = "+((num<<2)+(num<<1)+ num));  
           System.out.println(" 8 * 20 = "+ ((num<<4) + (num<<2)));  
           System.out.println(" 8 * 39 = "+ ((num<<5)+(num<<2) + (num<<1)+num));  
      }  
 }  

The output of the above program is as follows: -

 8 * 7 = 56  
 8 * 20 = 160  
 8 * 39 = 312  

In this way, every numbers can be represented in terms of bits and can be multiplied easily.

Also decimal numbers which can be expressed in binary can also be multiplied with the help of bits. I am presenting some examples.

 public class MultiplyBits {  
      public static void main (String args[])  
      {  
           int num =8;  
           System.out.println(" 8 * 0.75 = "+((num>>2)+(num>>1)));  
           System.out.println(" 8 * 17.25 = "+ ((num<<4) + (num>>2) + num));  
           System.out.println(" 8 * 1.5 = "+ ((num)+(num>>1)));  
      }  
 }  

The output of the above program is as follows -

 8 * 0.75 = 6  
 8 * 17.25 = 138  
 8 * 1.5 = 12  

I hope everyone liked the post. Please comment below if you have any doubts. All comments will be responded soon.

Thanks for reading the post.

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++