按位乘以 5/8 观察溢出错误

问题描述 投票:0回答:1

我一直在尝试找出代码中的错误,但我似乎无法找出错误是什么。我已经走过了每一行,这是有道理的。

目标是乘以 5/8 舍入到 0 并防止溢出。运算顺序是乘以 5,然后除以 8(即 11 * 5/8 = 6)。优化的目标是使用 12 个或更少的运算符。

规定仅此而已! 〜& ^ | + << >> 操作

我目前尝试的解决方案是

    int mul = (x << 2) + x;   // multiplying by 5

    int bias = (mul >> 31) & 7;   // add 2^3 - 1 = 7 before right shift if number is negative

    int result = (mul + bias) >> 3;  // divide by 8 after adding the bias

    return result;
}

我收到这条消息

错误:测试 trueFiveEighths(-2147483648[0x80000000]) 失败... ...给出 -268435456[0xf0000000]。应该是-1342177280[0xb0000000]

c bitwise-operators
1个回答
0
投票

也许将 1/8 + 1/2 (4/8) 相加会更好。试试

return ( x >> 1 ) | ( x >> 3 );

© www.soinside.com 2019 - 2024. All rights reserved.