c,python: Use little-endina byte order for bigint arithmetics

This better matches what one would expect from the hex or base64
(upcoming) formats.
This commit is contained in:
2021-11-15 01:13:17 +01:00
parent cc473f4c24
commit bcae51ead9
7 changed files with 51 additions and 56 deletions

View File

@ -23,10 +23,13 @@ void bhash_fini(bhash_t *bh)
free(bh->bh_data);
}
/*
* Treat the bhash as a bigint in `little-endian` notation and perform a 32-bit
* division of the whole hash. Return the modulo.
*/
uint32_t bhash_mod32(bhash_t *bh, uint32_t mod)
{
uint32_t *pi;
uint32_t *pend;
uint8_t *pdata;
uint64_t n;
uint32_t rv = 0;
@ -36,15 +39,25 @@ uint32_t bhash_mod32(bhash_t *bh, uint32_t mod)
return BHASH_MOD32_ERR;
}
pend = (uint32_t *)(bh->bh_data + bh->bh_len);
pdata = bh->bh_data + bh->bh_len;
for (pi = (uint32_t *)bh->bh_data; pi < pend; pi++)
for (pdata = bh->bh_data + bh->bh_len - sizeof(uint32_t);
pdata >= bh->bh_data;
pdata -= sizeof(uint32_t))
{
n = (uint64_t)rv << (sizeof(uint32_t) * 8);
n |= htonl(*pi);
n |= (uint32_t)pdata[0];
n |= (uint32_t)pdata[1] << 8;
n |= (uint32_t)pdata[2] << 16;
n |= (uint32_t)pdata[3] << 24;
*pi = ntohl(n / mod);
rv = n % mod;
n /= mod;
pdata[0] = n >> 0;
pdata[1] = n >> 8;
pdata[2] = n >> 16;
pdata[3] = n >> 24;
}
bh->bh_bits_used += log(mod) / log(2);