X >>= N 做什么?
What X >>= N does?
我有这个代码:
tmp = (uint)len;
writer.CurPosition = value + 1;
do
{
value++;
writer.dest.WriteByte((byte)((tmp & 0x7F) | 0x80));
} while ((tmp >>= 7) != 0);
但我不明白 tmp >>= 7
是如何工作的?
>>
是位移运算符
tmp >>= 7
向右移动 tmp
7 位并将其设置为该值。
循环将继续,直到 tmp
为 0
>>
被称为对bitwise-shift的运算符。并且由于在 >>
之后还有附加的 =
(形成 复合赋值 运算符 >>=
),因此 赋值 和 assigner 变量 (tmp
) 将被 shared。
换句话说,使用给定的示例,
tmp >>= 7; //actually you use tmp both to assign and to be assigned
等同于
tmp = tmp >> 7; //actually you use tmp both to assign and to be assigned
下面说一下bitwise-shift的操作,我觉得最好还是举例说明一下吧
假设tmp
的值为0xFF00
(二进制表示为1111 1111 0000 0000
),那么如果我们按位来看,>>=
的操作看起来像这样
1111 1111 0000 0000 //old tmp
------------------- >> 7
0000 0001 1111 1110 //Shifted by 7 -> this is going to be the new value for tmp
因此,tmp
的新值将是 0x01FE
(即 0000 0001 1111 1110
)
这实际上是C和C++的一部分,叫做Compound assignment operator。
tmp >>= 7
等同于
tmp = tmp >> 7
以>>
作为按位右移。
我有这个代码:
tmp = (uint)len;
writer.CurPosition = value + 1;
do
{
value++;
writer.dest.WriteByte((byte)((tmp & 0x7F) | 0x80));
} while ((tmp >>= 7) != 0);
但我不明白 tmp >>= 7
是如何工作的?
>>
是位移运算符
tmp >>= 7
向右移动 tmp
7 位并将其设置为该值。
循环将继续,直到 tmp
为 0
>>
被称为对bitwise-shift的运算符。并且由于在 >>
之后还有附加的 =
(形成 复合赋值 运算符 >>=
),因此 赋值 和 assigner 变量 (tmp
) 将被 shared。
换句话说,使用给定的示例,
tmp >>= 7; //actually you use tmp both to assign and to be assigned
等同于
tmp = tmp >> 7; //actually you use tmp both to assign and to be assigned
下面说一下bitwise-shift的操作,我觉得最好还是举例说明一下吧
假设tmp
的值为0xFF00
(二进制表示为1111 1111 0000 0000
),那么如果我们按位来看,>>=
的操作看起来像这样
1111 1111 0000 0000 //old tmp
------------------- >> 7
0000 0001 1111 1110 //Shifted by 7 -> this is going to be the new value for tmp
因此,tmp
的新值将是 0x01FE
(即 0000 0001 1111 1110
)
这实际上是C和C++的一部分,叫做Compound assignment operator。
tmp >>= 7
等同于
tmp = tmp >> 7
以>>
作为按位右移。