小编Dan*_*Dan的帖子

在C中实现逻辑右移

我正在使用仅按位运算符在C中创建逻辑右移位函数.这就是我所拥有的:

int logical_right_shift(int x, int n)
{
    int size = sizeof(int); // size of int

    // arithmetic shifts to create logical shift, return 1 for true
    return (x >> n) & ~(((x >> (size << 3) - 1) << (size << 3) -1)) >> (n-1);
}
Run Code Online (Sandbox Code Playgroud)

这实际上适用于所有情况,除非n = 0.我一直试图找到一种方法来解决它,所以它也适用于n = 0,但我卡住了.

c bit-manipulation

16
推荐指数
3
解决办法
5万
查看次数

标签 统计

bit-manipulation ×1

c ×1