Adding 64 bit numbers using 32 bit arithmetic

前端 未结 6 885
渐次进展
渐次进展 2020-12-05 06:02

How do we add two 64 bit numbers using 32 bit arithmetic??

6条回答
  •  庸人自扰
    2020-12-05 06:23

    it looks something like this

    /* 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;
    }
    

    Actual hardware doesn't use 32 bits to add 16 bits at a time, only one extra bit of carry is ever needed for addition, and almost all CPU's have a carry status flag for when an addition operation overflowed, so if you are using a 32 bit cpu, you can add 64 bit operands in two, 32 bit operations.

提交回复
热议问题