Implementing Logical Right Shift in C

后端 未结 8 1041
心在旅途
心在旅途 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:32

    Derived from php's implementation of logical right shifting

    function logical_right_shift( i , shift ) {
    
        if( i & 2147483648 ) {
            return ( i >> shift ) ^ ( 2147483648 >> ( shift - 1 ) );
        }
    
        return i >> shift;
    }
    

    For 32bit platforms only.

    0 讨论(0)
  • 2020-11-29 07:39
    int logicalShift(int x, int n) {
      int mask = x>>31<<31>>(n)<<1;
      return mask^(x>>n);
    }
    

    Only for 32 bits

    0 讨论(0)
提交回复
热议问题