简体   繁体   English

按位移位澄清

[英]Bitwise Shift Clarification

Assume I have the variable x initialized to 425 . 假设我将变量x初始化为425 In binary, that is 110101001 . 二进制形式为110101001

Bitshifting it to the right by 2 as follows: int a = x >> 2; 如下将其向右移2位: int a = x >> 2; , the answer is: 106 . ,答案是: 106 In binary that is 1101010 . 以二进制形式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; 如下将其向左移2位: int a = x << 2; , the answer is: 1700 . ,答案是: 1700 In binary this is 11010100100 . 二进制形式是11010100100 I don't understand how this works. 我不明白这是怎么回事。 Why are the two left most bits preserved? 为什么保留最左边的两个位? How can I drop them? 我该如何丢弃它们?

Thank you, 谢谢,

This is because int is probably 32-bits on your system. 这是因为int在您的系统上可能是32位。 (Assuming x is type int .) (假设x是int类型。)

So your 425 , is actually: 因此,您的425实际上是:

0000 0000 0000 0000 0000 0001 1010 1001

When left-shifted by 2, you get: 当左移2时,您将得到:

0000 0000 0000 0000 0000 0110 1010 0100

Nothing gets shifted off until you go all the way past 32. (Strictly speaking, overflow of signed-integer is undefined behavior in C/C++.) 直到您超过32位,一切都不会改变。(严格来说,有符号整数的溢出是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: 要丢弃移位的位,您需要对数字的原始长度的掩码进行按位与运算:

int a = (425 << 2) & 0x1ff;  //  0x1ff is for 9 bits as the original length of the number.

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 ? 其次,如果可以使用* 4/ 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: 如果要在数学上“在左侧截断”,请执行模运算:

(x * 4) % 256

The bitwise equivalent is AND with a bit pattern: (x << 2) & 0xFF 按位等效为与(AND),具有以下位模式: (x << 2) & 0xFF

(That is, the fundamental unsigned integral types in C are always implicitly "modulo 2 n ", where n is the number of bits of the type.) (也就是说,C中的基本无符号整数类型始终隐式为“模2 n ”,其中n是该类型的位数。)

Why would you expect them to be dropped? 您为什么期望它们被丢弃? Your int (probably) consumes 4 bytes. 您的int(可能)消耗4个字节。 You're shifting them into a space that it rightfully occupies. 您正在将它们转移到正确占用的空间中。

The entire 4-byte space in memory is embraced during evaluation. 评估期间将占用存储器中的整个4字节空间。 You'd need to shift entirely out of that space in memory to "drop" them. 您需要完全移出内存中的该空间以“删除”它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM