gpt4 book ai didi

c - 乘以 5/8 并观察溢出

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:19 25 4
gpt4 key购买 nike

我真的很接近最终打破这个东西,但我仍然不知道如何观察它的溢出。

int multFiveEighths(int x) {

int y=((x<<2)+x);
int f=((y>>3)+1);
int z=(y>>3);



return f + ((~!(x>>31&1)+1) & (z+~f+1));

我乘以 5/8,并使用条件位表示:如果符号位为 1(数字为负),则使用 f,否则使用 z。

其中一部分是包括溢出行为,如 C 表达式 (x*5/8)

那么如何包含溢出行为呢?我只能使用这些操作:! ~ & ^ | + << >>没有循环,没有转换,没有函数声明。我靠得太近了,这很痛苦。

编辑

我必须实现向零舍入。

最佳答案

int x = num >> 3; // divide by 8 (only defined for positive values)

x = x << 2 + x; // multiply by 5; no overflow yet since 5/8 is less than one

int y = num & 7; // the bits we shifted out

y = y << 2 + y; // multiply by 5; no overflow

return (x + (y >> 3)); // the two pieces

附录,负数向零舍入:

int s = -((num >> 31) & 1); // sign bit as -1 or 0

int n = (num ^ s) - s; // twos complement if negative

int x = n >> 3; // divide by 8

x = (x << 2) + x; // multiply by 5; no overflow yet since 5/8 is less than one

int y = n & 7; // the bits we shifted out

y = (y << 2) + y; // multiply by 5; no overflow

return (s ^ (x + (y >> 3))) - s; // the two pieces and complemented back

关于c - 乘以 5/8 并观察溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12608159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com