Implementing Logical Right Shift in C

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

    As with @Ignacio's comment, I don't know why you would want to do this (without just doing a cast to unsigned like in the other answers), but what about (assuming two's complement and binary, and that signed shifts are arithmetic):

    (x >> n) + ((1 << (sizeof(int) * CHAR_BIT - n - 1)) << 1)
    

    or:

    (x >> n) ^ ((INT_MIN >> n) << 1)
    

提交回复
热议问题