Are the shift operators (<<, >>) arithmetic or logical in C?

后端 未结 11 1608
粉色の甜心
粉色の甜心 2020-11-22 07:52

In C, are the shift operators (<<, >>) arithmetic or logical?

11条回答
  •  無奈伤痛
    2020-11-22 08:31

    Here are functions to guarantee logical right shift and arithmetic right shift of an int in C:

    int logicalRightShift(int x, int n) {
        return (unsigned)x >> n;
    }
    int arithmeticRightShift(int x, int n) {
        if (x < 0 && n > 0)
            return x >> n | ~(~0U >> n);
        else
            return x >> n;
    }
    

提交回复
热议问题