Search code examples
c++cdivision

How can I extend my code do divide by a 64bit integer? (128bit / 64bit)


My problem is that my Code just divides the 128bit by a 32bit integer but not by a 64bit. I know there are some instructions like _umul128() or __uint128_t for this, but I need a portable version.

The code only work when the divisor is smaller than a uint32_t and I don`t know why.

uint64_t udiv32(uint64_t high, uint64_t low, uint32_t divisor, uint32_t* rem)
{
    uint64_t q0, r0;
    uint64_t q1, r1;
    uint64_t temp;

    const uint32_t a_lo = low & 0xFFFFFFFF;
    const uint32_t a_hi = low >> 32;

    r0 = high % divisor;

    temp = ((r0 << 32) | a_hi);
    q1 = temp / divisor;
    r1 = temp % divisor;

    temp = ((r1 << 32) | a_lo);
    q0 = temp / divisor;
    r0 = temp % divisor;

    *rem = r0;
    return ((q1 << 32) | q0);
}

Maybe someone can help me to extend the function so that the divisor can be a uint64_t. Also pls no hate im new to this :)


Solution

  • The function presented appears to implement the long division algorithm in base 232, for the specific case of a dividend with up to four (big) digits and a one-(big-)digit divisor. It will not handle divisors larger than 232-1 even if you give the divisor parameter a wider type.

    How can I extend my code do divide by a 64bit integer?

    Your best alternative would probably be two write a separate version specific to the 128-bit / 64-bit case. You could do that in base 264, making it simpler than the 128-bit / 32-bit version. There is no good way to reuse the existing code itself for the purpose, though you could look to it for inspiration. This is not a coding service, however, so I leave the details to you.