29

How can I multipy two integers using bitwise operators?

I found an implementation here. Is there a better way of implementing multiplication?

For example: 2 * 6 = 12 must be performed using bitwise operators.

NOTE: Numbers are arbitrary, not power of 2

JJJ
  • 32,902
  • 20
  • 89
  • 102
SuperMan
  • 3,532
  • 12
  • 45
  • 49
  • Does it have to take arbitrary integers? There's an easy way to implement multiplication if one of the operands has to be a power of two. Also, is this a homework assignment or are you trying to implement multiplication in assembly on a processor with an instruction set that doesn't include multiplication (or both)? – In silico Dec 16 '10 at 00:57
  • power of two implementation is easy, but in this case integers are not power of two they are arbitrary. And it is not Homework question, its an interview question. Please check the implementation i have attached. – SuperMan Dec 16 '10 at 00:58
  • The link in the question doesnt exist – AlphaGoku Oct 13 '16 at 05:27
  • The Wikipedia entry on [bitwise operator applications](http://en.wikipedia.org/wiki/Bitwise_operation#Applications) has some pseudo code, but it uses the addition operator as well as bitwise operators. – JonMR Dec 16 '10 at 01:05

7 Answers7

46
#include <stdio.h>

int main(void)
{
    int a, b, result;
    printf("Enter the numbers to be multiplied:");
    scanf("%d%d", &a, &b);       // a > b
    result = 0;
    while (b != 0)               // Iterate the loop till b == 0
    {
        if (b & 1)               // Bitwise & of the value of b with 1
        {
            result = result + a;  // Add a to result if b is odd .
        }
        a <<= 1;                    // Left shifting the value contained in 'a' by 1
                                  // Multiplies a by 2 for each loop
        b >>= 1;                    // Right shifting the value contained in 'b' by 1.
    }

    printf("Result: %d\n",result);
}

Source

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
zengr
  • 38,346
  • 37
  • 130
  • 192
  • 1
    @Vector9 Do you have a specific thing you need to understand? The heart of the logic is multiplying a value by 2 and adding it up to the result whenever the other value is odd. It used bit shifting to multiply(left) /divide(right) the 2 inputs. Thinking it in terms of arithmetic operators: `while(b != 0): if(b is odd) {result = result + a;} a = a * 2; b = b/2;`. A simple mathematical trick.@Shiv's trick is even neater where he avoided `result = result + a` – zengr Oct 13 '16 at 18:22
  • Yes i understood wat ur doing: a*b*(2/2)--> (a*2)*(b/2). What i didnt get was why result = result + a is used when odd. – AlphaGoku Oct 14 '16 at 04:17
  • what is the time complexity of this? – sorry_I_wont Feb 22 '17 at 20:04
  • Its O(b) (since a is multiplied b times) – zengr Feb 22 '17 at 22:37
  • 1
    @zengr it's O(log(b)), because b is divided by two each iteration. – Ilya Schukin May 30 '18 at 10:12
  • It's O(log2(b)), not O(log(b))! Logarithmic bases! Also, what if B isn't a power of 2? – wallabra Dec 03 '18 at 16:33
10

I came here looking for this question and I find Zengr's answer correct. Thanks Zengr! But there is one modification I would want to see which is getting rid of the '+' operator in his code. This should make multiplication of two arbitrary numbers using NO ARITHMETIC OPERATORS but all bitwise.

Zengr's solution first:

#include<stdio.h>
main()
{
   int a,b,result;     
   printf("nEnter the numbers to be multiplied :");
   scanf("%d%d",&a,&b);         // a>b
   result=0;
   while(b != 0)               // Iterate the loop till b==0
   {
        if (b&01)                // Bitwise &  of the value of b with 01
        {
          result=result+a;     // Add a to result if b is odd .
        }
        a<<=1;                   // Left shifting the value contained in 'a' by 1 
                           // multiplies a by 2 for each loop
        b>>=1;                   // Right shifting the value contained in 'b' by 1.
   }
   printf("nResult:%d",result);
}

My Answer would be:

#include<stdio.h>
main()
{
   int a,b,result;     
   printf("nEnter the numbers to be multiplied :");
   scanf("%d%d",&a,&b);         // a>b
   result=0;
   while(b != 0)               // Iterate the loop till b==0
   {
        if (b&01)                // Bitwise &  of the value of b with 01
        {
          result=add(result,a);     // Add a to result if b is odd .
        }
        a<<=1;                   // Left shifting the value contained in 'a' by 1 
                                // multiplies a by 2 for each loop
        b>>=1;                   // Right shifting the value contained in 'b' by 1.
   }
   printf("nResult:%d",result);
}

where I would write add() as:

int Add(int x, int y)
{
    // Iterate till there is no carry  
    while (y != 0)
    {
        // carry now contains common set bits of x and y
        int carry = x & y;  

        // Sum of bits of x and y where at least one of the bits is not set
        x = x ^ y; 

        // Carry is shifted by one so that adding it to x gives the required sum
        y = carry << 1;
    }
    return x;
}

or recursively adding as:

int Add(int x, int y)
{
    if (y == 0)
        return x;
    else
        return Add( x ^ y, (x & y) << 1);
}

source for addition code: http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/

Shiv
  • 471
  • 4
  • 8
5

This one is purely with bit-wise operations.

public int bitwiseMultiply(int a, int b) {
    if (a ==0  || b == 0) {
        return 0;
    }

    if (a == 1) {
        return b;
    }
    else
        if (b == 1) {
            return a;
        }


    int result = 0; // Not needed, just for test
    int initA = a;
    boolean isORNeeded = false;
    while (b != 0 ) {

        if (b == 1) {
            break;
        }

        if ((b & 1) == 1) { // Carry needed, odd number
            result += initA; // Test, not needed
            isORNeeded = true;
        }

        a <<= 1; // Double the a
        b >>= 1; // Half the b
        System.out.println("a=["+a+"], b=["+b+"], result=["+result+"]");
    }

    return (isORNeeded ? (a | initA) : a); // a + result;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
artofabhishek
  • 275
  • 1
  • 4
  • 9
2

Assembly algorithm: This follows directly from the fact that ax*7 = (ax*8)-ax.

mov     bx, ax          ;Save AX*1
shl     ax, 1           ;AX := AX*2
shl     ax, 1           ;AX := AX*4
shl     ax, 1           ;AX := AX*8
sub     ax, bx          ;AX := AX*7

Every shift step is a multiplication by 2

Conex
  • 832
  • 8
  • 17
0

In C# here is the implementation of the function.

    public static int Mul(int a, int b)
    {
        int r = 0;
        while (b != 0)
        {
            var temp = b & 1;

            if (temp!= 0)
            {
                r = r + a;
            }
            a= a << 1;
            b= b >> 1;
            if (temp == 0)
            {
                r = a;
                break;
            }
        }

        return r;
    }
Ranjan
  • 17
  • 1
  • 1
    This answer contains a mistake. I submitted an edit, asking a moderator to remove the mistake, and this was his response: _Edits that change code in answers are almost always rejected. You need to either leave a comment under the answer, or a new answer of your own._ The mistake in the above code is `if (temp == 0)`. The entire if statement including the break should be removed. To see this, call the function with inputs of 1 and 4: Mul(1, 4), and the return value will be 2. Clearly 1 x 4 is not 2. – Barzee Nov 15 '13 at 01:14
  • this code directs to mistakes. And why didnt you examine the posted codes(accepted answer)? – Fredrick Gauss Oct 21 '14 at 05:38
-1
    #include<stdio.h>
    void main()
    {
        int n, m, i, j, x, large, small, t1, m2, result, a1, a2, a3, c, c1, c2, r, r1, la, re;

        printf("Enter two numbers\n");
        scanf("%d%d", &n, &m);
        result = 0;

        if (n > m)
        {
            large = n;
            small = m;
        }
        else
        {
            large = m;
            small = n;
        }

        c = 0;

        while (small)
        {
            t1 = small;
            t1 &= 1;

            if (t1 == 1)
            {
                printf("\n %d", large);
                la = large;
                re = result;
                m2 = 0;
                r1 = 1;
                while (re || la || c)
                {
                    a2 = la;
                    a2 &= 1;
                    a3 = re;
                    a3 &= 1;

                    c1 = a2 & a3;
                    r = a3 ^ a2;

                    c2 =r & c;
                    r ^= c;
                    if (c1 || c2)
                        c = 1;
                    else
                        c = 0;

                    result &= ~r1;
                    x = r;
                    m2 >>= 1;
                    while (m2)
                    {
                        r <<= 1;
                        m2 >>= 1;
                    }

                    result |= r;
                    la >>= 1;
                    re >>= 1;
                    r1 <<= 1;
                    m2 = r1;
                }

            }
            large <<= 1;
            small >>= 1;

        }
        printf("\n%dX%d= %d\n", n, m, result);
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ajay Anto
  • 7
  • 1
-1

Below is one possible solution for multiplication of two integers using bitwise operators.

#include <stdio.h>
#define INT_BITS 32

int multiply(int a, int b)
{
    int pos1, pos2, res;
    for (pos1 = 0; pos1 < INT_BITS; pos1++)
      {
        for (pos2 = 0; pos2 < INT_BITS; pos2++)
          {
            /* Find the bits set in both numbers and add their
             * corresponding powers of 2. 
             */
            if ((a & (1 << pos1)) && (b & (1 << pos2)))
              {
                res = res + (1 << (pos1 + pos2));
                // res = res + ((1 << pos1) << pos2);
                /* Both the above statements calculating res are same */
              }
          }
      }

  return res;
}


int main()
{
    int num1, num2, product;
    printf("Enter two numbers to be multiplied:");
    scanf("%d %d", &num1, &num2);
    product = multiply(num1, num2);
    printf("Product of %d and %d: %d\n", num1, num2, product);
    return 0;
}

Function multiply() can be slighted changed as below using Shiv's Add() function:

int Add(int x, int y)
{
    if (y == 0)
        return x;
    else
        return Add( x ^ y, (x & y) << 1);
}

int multiply(int a, int b)
{
    int pos1, pos2, res, temp;
    for (pos1 = 0; pos1 < INT_BITS; pos1++)
      {
        for (pos2 = 0; pos2 < INT_BITS; pos2++)
          {
            /* Find the bits set in both numbers and add their
             * corresponding powers of 2. 
             */
            if ((a & (1 << pos1)) && (b & (1 << pos2)))
              {
                temp = (1 << pos1) << pos2;
                res = Add(res, temp);
              }
          }
      }

  return res;
}