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

后端 未结 8 1706
挽巷
挽巷 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:06

    I don't see any major problem in using >> but still if you want to do arithmetic right shift then you can divide the number by 2 to the power x, where x is the amount of right shift you want to do because dividing a number by two is equivalent to a single right shift.

    Let's say you want to do a >> x. Then it can also be achieved by doing a / (int)pow(2,x). pow(2,x) is the mathematical power or you can also take it as 2 to the power x.

提交回复
热议问题