Dividing by power of 2 using bit shifting

后端 未结 4 904
失恋的感觉
失恋的感觉 2020-12-28 23:05

I\'ve got the following task:

Compute x/(2^n), for 0 <= n <= 30 using bit shifting.

Requirement: Round toward zero

4条回答
  •  臣服心动
    2020-12-28 23:14

    public int DivideByPowerOf2(int x, int n)
        {
    
            return (x + ((x >> 31) & ((1 << n) + ~0))) >> n;
        }
    

提交回复
热议问题