【发布时间】:2012-08-08 01:11:23
【问题描述】:
我想知道在进行位移时是否需要在检索存储在某个字节处的值之前屏蔽一个数字。
以这段代码为例:
short b1 = 1;
short b2 = 2;
short b0 = (short)((b1 << 8) | b2); //store two values in one variable
Console.WriteLine(b0); //b1 and b2 combined
Console.WriteLine((b0 & (255 << 8)) >> 8); //gets the value of b1
就我而言,进行右移会丢弃所有小于您已移位的位数的位。因此,将b0 右移 8 位将丢弃b2 的 8 位,只留下b1。
Console.WriteLine(b0 >> 8); //this also gets b1!!
我想知道,在转换得到b1 的值之前,是否需要用255 << 8 屏蔽b0?
注意:
在检索值之前,我唯一能想到的屏蔽是是否在更高字节处存储了其他内容,例如尝试取回 b2 的值,其中将使用此代码:
Console.WriteLine(b0 & 255); //gets the value of b2
【问题讨论】:
-
如果您将
b1和b2bytes 和b0设置为ushort,这将非常明显。右移ushort不会传播符号位。
标签: c# bit-manipulation bit-shift