HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Mockup in C of hardware implementation for multiplication of signed integers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
multiplicationhardwaremockupforsignedimplementationintegers

Problem

I challenged myself to implement multiplication of signed integers using only +, -, >>, <<, &, |, ^, and conditionals, though I would like to improve my method to not use conditionals if possible in the future. Any input would be very helpful.

#include 
#include 
#include 
#include 
#include 

int multiply(int, int);

int main() {
    int a, b, c, i;
    bool equal;

    srand(time(NULL));

    for (i = 0; i >= 1));

    return sign | (prod & INT_MAX);
}

Solution

Sign bit manipulation unnecessary

I looked at your code and was puzzled by all the sign bit manipulation. As far as I can tell, it's not necessary. I rewrote your function to be like the following and it still passed all your tests:

int multiply(int a, int b)
{
    // Bit keeps track of mask bit index.
    struct {
        unsigned int index: 5;
    } bit = {31};
    int prod = 0;

    do {
        prod += ((a & (1 << bit.index)) ? b << bit.index : 0);
    } while (bit.index--);

    return prod;
}


Bonus answer: no conditionals inside loop

int multiply(int a, int b)
{
    // Bit keeps track of mask bit index.
    struct {
        unsigned int index: 5;
    } bit = {31};
    int prod = 0;

    do {
        prod += (-((a >> bit.index) & 1)) & (b << bit.index);
    } while (bit.index--);

    return prod;
}


Explanation:

  • ((a >> bit.index) & 1) is 1 or 0 depending on the masked bit. Call this B.



  • -B is -1 or 0. This sets up a mask to use for the next step (-1 is a mask of all one bits).



  • `-B & (b

Code Snippets

int multiply(int a, int b)
{
    // Bit keeps track of mask bit index.
    struct {
        unsigned int index: 5;
    } bit = {31};
    int prod = 0;

    do {
        prod += ((a & (1 << bit.index)) ? b << bit.index : 0);
    } while (bit.index--);

    return prod;
}
int multiply(int a, int b)
{
    // Bit keeps track of mask bit index.
    struct {
        unsigned int index: 5;
    } bit = {31};
    int prod = 0;

    do {
        prod += (-((a >> bit.index) & 1)) & (b << bit.index);
    } while (bit.index--);

    return prod;
}

Context

StackExchange Code Review Q#90875, answer score: 7

Revisions (0)

No revisions yet.