Saurabh
Saurabh

Reputation: 29

create your own my128int data type with the help of inbuilt c data type

I want to create my own data type which can hold values from -2^127 to 2^127-1 and want to perform addition on two my128int data type variable. I search on stackoverflow community and found custom data type in C

What additional task is required from the above discussed thread.

void addition(my128int a, my128int b)
{
    ....
    //perform some task
    // print the result a+b
}

Upvotes: 2

Views: 990

Answers (1)

John Bollinger
John Bollinger

Reputation: 180171

For an integer data type, I don't much care for the solution offered in the (unaccepted) answer to the question you referenced.

Myself, I would implement a type such as you describe like this:

typedef struct myint128_s {
    uint32_t bits[4];
} myint128;

Addition would then look like this:

void myint128_add(myint128 *addend1, myint128 *addend2, myint128 *sum) {
    uint32_t carry = 0;
    int i;

    for (i = 0; i < 4; i += 1) {
        uint64_t temp = (uint64_t) addend1->bits[i]
                + (uint64_t) addend2->bits[i] + carry;
        sum->bits[i] = (uint32_t) temp;
        carry = (uint32_t) (temp >> 32);
    }

    /* can detect overflow here, if desired */
}

This assumes / provides a twos complement representation of negative numbers, consistent with the bounds you specified for representable numbers. You don't then have to give any special attention to the sign bit (bit 63 of bits[3]).

In effect, this is a numeric representation in base 2^32.

Upvotes: 4

Related Questions