Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.40/5 (3 votes)
See more:
C#
How to multiply two binary numbers without " * " operator? In c rrogramming


What I have tried:

I write this program for integer values.

#include<stdio.h>
/* function to multiply two numbers x and y*/
int multiply(int x, int y)
{
   /* 0  multiplied with anything gives 0 */
   if(y == 0)
     return 0;
 
   /* Add x one by one */
   if(y > 0 )
     return (x + multiply(x, y-1));
  
  /* the case where y is negative */
   if(y < 0 )
     return -multiply(x, -y);
}
 
int main()
{
  printf("\n %d", multiply(5, -11));
  getchar();
  return 0;
}
Posted
Updated 5-Nov-16 18:41pm

It depends exactly what your homework question is asking for: if you are supposed to write a multiply function which doesn;t use the multiply operator, then there are a couple of ways you could approach this:
1) Brute force and ignorance. x * y is the same as adding x to itself y times:
x * 0 = 0
x * 1 = x
x * 2 = x + x
x * 3 = x + x + x
...
So find the smallest of the two numbers, and loop that many times, adding the other to a total.
2) A bit more finesse. Remember logarithms? logn(x * y) = logn(x) + logn(y)
So you could use the C built in math functions to log10 x and y, add then and then anti log them to get the result.
3) A lot more finesse! Use bit shift and add in a loop to multiply. An integer is a binary number, so you can treat each bit as a multiplier: Multiplying and Dividing Binary Numbers | Multiplication and Division[^] - ANDing a number with 1 tells you if the least significant bit is zero or one, and the two shift operators << and >> multiply and divide by two.

But ... this is your homework, so I'll give you no code!
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 30-Oct-16 9:24am    
Even helpful for me. 5ed.
Rahul VB 30-Oct-16 10:59am    
Commonly asked question and a perfect solution.
My 5!
Sorry for late answer.
When you learned to do multiplications in primary school, you should have learned this efficient algorithm:
  456
 *123
-----
 1368
 912.
456..
-----
46088

it use the trick that multiplying by 10 is easy, you just shift digits and add a zero on right.
It just happen that this algorithm is usable for binary multiplication because processors know how to do the shift on binary values.
All you need is bitwize operators: Bitwise operations in C - Wikipedia[^]
multiply by -1: 0-x
multiply by  2: x << 1
divide by 2: x >> 1
Check if unit is 0 or 1: x & 1
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900