how to perform a 64-bit addition in c? but the following code fails? why?

I have taken this code from stack overflow. But this doesnot works. Pls help me. I need to perform 64-bit addition in c. I am using 32-bit compiler.
:chomp: :chomp:
/* break up the 64bit number into smaller, 16bit chunks */
struct longint {
uint16 word0;
uint16 word1;
uint16 word2;
uint16 word3;

uint16 add(longint *result, longint *a, longint *b)
/* use an intermediate large enough to hold the result
of adding two 16 bit numbers together. */
uint32 partial;

/* add the chunks together, least significant bit first */
partial = a->word0 + b->word0;

/* extract thie low 16 bits of the sum and store it */
result->word0 = partial & 0x0000FFFF;

/* add the overflow to the next chunk of 16 */
partial = partial >> 16 + a->word1 + b->word1;
/* keep doing this for the remaining bits */
result->word1 = partial & 0x0000FFFF;
partial = partial >> 16 + a->word2 + b->word2;
result->word2 = partial & 0x0000FFFF;
partial = partial >> 16 + a->word3 + b->word3;
result->word3 = partial & 0x0000FFFF;
/* if the result overflowed, return nonzero */
return partial >> 16;

When you say it fails I assume you mean gives the wrong result?

This line of code is the issue

partial = a->word0 + b->word0;

word0 in your structure is 16 bits and you are on a 16 bit platform/compiler so this will perform the calculation in 16 bits and then convert it to 32 bits to store it in partial. Since the calculation is in 16 bits carry of the addition is discarded.

You need to do the calculation in 32 bits in order to keep the carry, you can do this by simply casting your variables in the calculation to 32 bits before doing the addition.

partial = (uint32)a->word0 + (uint32)b->word0;

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.