Are the shift operators (<<, >>) arithmetic

2018-12-31 16:28发布

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

11条回答
大哥的爱人
2楼-- · 2018-12-31 16:58

According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values.

Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values.

Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift.

查看更多
裙下三千臣
3楼-- · 2018-12-31 17:03

When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted.

(As background for those readers unfamiliar with the difference, a "logical" right shift by 1 bit shifts all the bits to the right and fills in the leftmost bit with a 0. An "arithmetic" shift leaves the original value in the leftmost bit. The difference becomes important when dealing with negative numbers.)

When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.

For example, assuming a 32 bit machine:

signed int x1 = 5;
assert((x1 >> 1) == 2);
signed int x2 = -5;
assert((x2 >> 1) == -3);
unsigned int x3 = (unsigned int)-5;
assert((x3 >> 1) == 0x7FFFFFFD);
查看更多
路过你的时光
4楼-- · 2018-12-31 17:03

will typically use logical shifts on unsigned variables and for left-shifts on signed variables. The arithmetic right shift is the truly important one because it will sign extend the variable.

will will use this when applicable, as other compilers are likely to do.

查看更多
爱死公子算了
5楼-- · 2018-12-31 17:08

Left shift <<

This is somehow easy and whenever you use the shift operator, it is always a bit-wise operation, so we can't use it with a double and float operation. Whenever we left shift one zero, it is always added to the least significant bit (LSB).

But in right shift >> we have to follow one additional rule and that rule is called "sign bit copy". Meaning of "sign bit copy" is if the most significant bit (MSB) is set then after a right shift again the MSB will be set if it was reset then it is again reset, means if the previous value was zero then after shifting again, the bit is zero if the previous bit was one then after the shift it is again one. This rule is not applicable for a left shift.

The most important example on right shift if you shift any negative number to right shift, then after some shifting the value finally reach to zero and then after this if shift this -1 any number of times the value will remain same. Please check.

查看更多
无与为乐者.
6楼-- · 2018-12-31 17:09

According to many compilers:

  1. << is an arithmetic left shift or bitwise left shift.
  2. >> is an arithmetic right shiftor bitwise right shift.
查看更多
美炸的是我
7楼-- · 2018-12-31 17:10

GCC does

  1. for -ve - > Arithmetic Shift

  2. For +ve -> Logical Shift

查看更多
登录 后发表回答