小编Ped*_*zzi的帖子

如何计算(a次b)除以c仅使用32位整数类型,即使b次不适合这种类型

请考虑以下内容作为参考实现:

/* calculates (a * b) / c */
uint32_t muldiv(uint32_t a, uint32_t b, uint32_t c)
{
    uint64_t x = a;
    x = x * b;
    x = x / c;
    return x;
}
Run Code Online (Sandbox Code Playgroud)

我感兴趣的是一个不需要64位整数类型的实现(在C或伪代码中).

我开始草拟一个如下概述的实现:

/* calculates (a * b) / c */
uint32_t muldiv(uint32_t a, uint32_t b, uint32_t c)
{
    uint32_t d1, d2, d1d2;
    d1 = (1 << 10);
    d2 = (1 << 10);
    d1d2 = (1 << 20); /* d1 * d2 */
    return ((a / d1) …
Run Code Online (Sandbox Code Playgroud)

c integer integer-overflow multiplication integer-division

5
推荐指数
1
解决办法
3254
查看次数