How can I perform arithmetic right shift in C in a portable way?

后端 未结 8 1712
挽巷
挽巷 2020-12-19 06:29

We are writing an emulator where we need sign propagating right shift. The emulated system uses 2\'s complement numbers.

I read that the >> operat

8条回答
  •  遥遥无期
    2020-12-19 07:17

    This function will work no matter the machine definition of 'int', by shifting the absolute value (i.e. without the sign) and then adding the sign:

    int shift(int value, int count)
    {
      return ((value > 0) - (value < 0)) * (abs(value) >> count);
    }
    

提交回复
热议问题