简体   繁体   中英

Remainder algorithm of byte array with unsigned int

Given a byte array in C++ (templated function) of a fixed size, and an unsigned integer, how can I calculate the remainder (normally the % operator for integers).

Here is how I currently do it using GMP:

template <typename HashType>
uint64_t remainder(const HashType& value, const uint64_t divisor)
{
    mpz_t integ;
    mpz_init(integ);
    mpz_import(integ, value.size(), 1, 1, 1, 0, value.data());
    uint64_t remainder = mpz_fdiv_ui(integ, divisor);
    mpz_clear(integ);
    return remainder;
}

It would be nice to remove the GMP dependency, and improve performance by not needing that setup and teardown code (just use the byte array directly).

BTW are there any algorithms where finding the remainder is faster but only for a certain subset of divisors (such as prime numbers)? (FYI this is used for hash buckets, so if I can choose the value of divisor)

If divisor can be more than 56 bits long, and you don't have a 128-bit integer type available, then you can't do this long division easily in a high-level language. So you should probably use either assembly language (for speed) or GMP (for ease of coding).

Does this answer your question? Or do you have constraints on the size of divisor ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM