我试图弄清楚算术位移运算符在C中是如何工作的,以及它将如何影响带符号的32位整数.
为简单起见,假设我们在一个字节(8位)内工作:
x = 1101.0101
MSB[ 1101.0101 ]LSB
Run Code Online (Sandbox Code Playgroud)
在Stack Overflow和一些网站上阅读其他帖子,我发现:
<<将转向MSB(在我的情况下向左),并用0填充"空"LSB位.
而>>会向着转向LSB(向右,在我的情况),并填写"空"与MS位位
因此,x = x << 7将导致LSB移动到MSB,并将所有内容设置为0.
1000.0000
Run Code Online (Sandbox Code Playgroud)
现在,让我说我会>> 7,最后的结果.这会导致[0000.0010]?我对吗?
关于转移运营商我的假设是对的吗?
我刚在我的机器上测试过,**
int x = 1; //000000000......01
x = x << 31; //100000000......00
x = x >> 31; //111111111......11 (Everything is filled with 1s !!!!!)
Run Code Online (Sandbox Code Playgroud)
为什么?
标准说:
1.3.24 [defns.undefined] undefined behavior behavior for which this International Standard imposes no requirements [ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to …