I'm writing a program to multiply two 4-bit number using add and shift method in C language. The code is as follows:

#include <stdio.h>
#include <math.h>

int main()
{
    int d,p=0, y=1010, x=1101, c, i;
    for(i=0;i<=3;i++)
    {
        c = x % 10;
        y = y << i;
        d = c*y;
        p = p ^ d;
        x = x / 10;
    }
    printf("%d",p);
    return 0;
}

I'm getting answer as 57570 which is wrong. Where am I going wrong?

Recommended Answers

All 2 Replies

shifting with 1 means multiplying by 2 in case of integer. shifting adds 0 left / right (depends on you) when the number is in binary. So, you can convert your integer into binary keeping the figure same. not the value. I mean integer 1010 will remain 1010 in binary. And then you can multiply using shifting operator. And it depends on you whwther you will print your result in binary or integer form.

Where am I going wrong?

If you had given your variables descriptive names so you could easily read through what your code is doing, or at least provided comments illuding to your train of thought when writing this program, you likely wouldn't have to ask us this question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.