Translating simple C code

235 views Asked by At

So I'm working on an assignment for my computer science course, We have to take an algorithm thats written in C and replicate it in assembly (SPARC). My issue is that I know very little C code since I specialize in java. Can anyone help me look at this code and give me its Java equivalent? If you guys have any tips on using it straight for SPARC, I'm open to those ideas too. Thanks!

neg = multiplier >= 0 ? 0 : 1;
product = 0;
for (i = 32; --i >= 0; ) {
    if (multiplier & 1)
        product += multiplicand;
    (product and multiplier registers) >> 1;
}
if (neg)
    product -= multiplicand;
3

There are 3 answers

0
COD3BOY On BEST ANSWER

This is a code to implement multiplication (though the given code is wrong) by yourself, without using * operator. See this snippet,

int multiplier, multiplicand,product=0;

/*Assume multiplier and multiplicand have their values*/

for(int i= multiplier;i>0;i--)
{
product+=multiplicand;
} 

Now code yourself to handle negative numbers.(Hope that now you know what the code does).The neg in your code is supposed to check if the multiplier is negative, but its not efficient to check only the multiplier,you should check both multiplier and multiplicand.

1
lc2817 On

The syntax of C is really close to the syntax of Java. Especially concerning this snipped so you shouldn't have any trouble to understand it.

Anyway I don't think that "and" exists in C.

Are you sure or your snippet?

What don't you understand in this code?

1
A.H. On

In that piece of code there is only one concept which is differnt in Java:

Pure C does not have boolean. So every comparison is true if the expression returns something else than zero. I see two places in the code where this matters.

Oh, and is not known in C either. Are you sure it is pure C? Also this one is surly not C:

(product and multiplier registers) >> 1;

I assume this means:

product >>= 1;     // or >>>=, depends on signed/unsigned
multiplier >>= 1;  // or >>>=, depends on signed/unsigned

If you know Java it should be no problem to understand what's going on with these hints.