作者:dmcm0005 | 来源:互联网 | 2023-01-21 06:35
Iamtryingtofigureouthowexactlyarithmeticbit-shiftoperatorsworkinC,andhowitwillaffe
I am trying to figure out how exactly arithmetic bit-shift operators work in C, and how it will affect signed 32-bit integers.
我正在试图弄清楚算术位移位操作符在C中是如何工作的,以及它将如何影响已签名的32位整数。
To make things simple, let's say we work within one byte (8 bits):
为了简单起见,假设我们在一个字节(8比特)内工作:
x = 1101.0101
MSB[ 1101.0101 ]LSB
Reading other posts on Stack Overflow and some websites, I found that: <<
will shift toward MSB (to the left, in my case), and fill "empty" LSB bits with 0s.
在Stack Overflow和一些网站上阅读其他文章,我发现:<<将向msb移动(在我的情况下),并填充“空”lsb位与0。
And >>
will shift toward LSB (to the right, in my case) and fill "empty" bits with MS bit
>>将向LSB(在我的情况下)向右移动,并将“空”位填充到MS比特。
So, x = x <<7
will result in moving LSB to MSB, and setting everything to 0s.
因此,x = x <<7将会使LSB移动到MSB,并将一切设置为0。
1000.0000
Now, let's say I would >> 7
, last result. This would result in [0000.0010]
? Am I right?
现在,假设我要>> 7,最后一个结果。这将导致[0000.0010]?我说的对吗?
Am I right about my assumptions about shift operators?
我对移动运营商的假设是否正确?
I just tested on my machine, **
我刚在我的机器上测试过。
int x = 1; //000000000......01
x = x <<31; //100000000......00
x = x >> 31; //111111111......11 (Everything is filled with 1s !!!!!)
Why?
为什么?
4 个解决方案