按位移位说明
假设我将变量 x
初始化为 425
。用二进制表示,即 110101001
。
将其向右移位 2,如下所示: int a = x >>> 2;,答案是:106
。二进制为 1101010
。这是有道理的,因为最右边的两个位被删除,并且两个零被添加到左侧。
将其向左移位 2,如下所示:int a = x << 2;,答案是:1700
。在二进制中,这是 11010100100
。我不明白这是如何运作的。为什么最左边的两个位被保留?我怎样才能丢掉它们?
谢谢你,
Assume I have the variable x
initialized to 425
. In binary, that is 110101001
.
Bitshifting it to the right by 2 as follows: int a = x >> 2;
, the answer is: 106
. In binary that is 1101010
. This makes sense as the two right-most bits are dropped and two zero's are added to the left side.
Bitshifting it to the left by 2 as follows: int a = x << 2;
, the answer is: 1700
. In binary this is 11010100100
. I don't understand how this works. Why are the two left most bits preserved? How can I drop them?
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为
int
在您的系统上可能是 32 位。 (假设 x 是int
类型。)因此,您的
425
实际上是:当左移 2 时,您会得到:
直到您完全过去,没有任何内容会被移动32.(严格来说,有符号整数的溢出是 C/C++ 中未定义的行为。)
要删除移出的位,您需要对作为数字原始长度的掩码进行按位 AND 操作:
This is because
int
is probably 32-bits on your system. (Assuming x is typeint
.)So your
425
, is actually:When left-shifted by 2, you get:
Nothing gets shifted off until you go all the way past 32. (Strictly speaking, overflow of signed-integer is undefined behavior in C/C++.)
To drop the bits that are shifted off, you need to bitwise AND against a mask that's the original length of your number:
首先,不要移动有符号整数。位运算仅对于无符号整数类型来说是普遍明确的。
其次,如果可以使用
* 4
和/ 4
为什么要转变?第三,当超出类型的大小时,仅删除左侧的位。如果您想在数学上“在左侧截断”,请执行模运算:
按位相当于与位模式的 AND:
(x << 2) & 0xFF
(也就是说,C 中的基本无符号整数类型始终隐式“模 2n”,其中 n 是该类型的位数。)
First off, don't shift signed integers. The bitwise operations are only universally unambiguous for unsigned integral types.
Second, why shift if you can use
* 4
and/ 4
?Third, you only drop bits on the left when you exceed the size of the type. If you want to "truncate on the left" mathematically, perform a modulo operation:
The bitwise equivalent is AND with a bit pattern:
(x << 2) & 0xFF
(That is, the fundamental unsigned integral types in C are always implicitly "modulo 2n", where n is the number of bits of the type.)
为什么你会期望它们被丢弃?你的 int (可能)消耗 4 个字节。你正在将它们转移到它正确占据的空间中。
评估期间会占用内存中的整个 4 字节空间。您需要完全移出内存中的该空间才能“删除”它们。
Why would you expect them to be dropped? Your int (probably) consumes 4 bytes. You're shifting them into a space that it rightfully occupies.
The entire 4-byte space in memory is embraced during evaluation. You'd need to shift entirely out of that space in memory to "drop" them.