Implementing Logical Right Shift in C

后端 未结 8 1125
心在旅途
心在旅途 2020-11-29 07:07

I\'m working on making a logical right shift function in C using only bitwise operators. Here\'s what I have:

int logical_right_shift(int x, int n)
{
    int         


        
8条回答
  •  执笔经年
    2020-11-29 07:25

    I think problem is in your ">> (n-1)" part. If n is 0 then left part will be shift by -1. So,here is my solution

    int logical_right_shift(int x, int n)
    {
      int mask = ~(-1 << n) << (32 - n);
      return  ~mask & ( (x >> n) | mask); 
    }
    

提交回复
热议问题