我想知道在进行位移位时,在检索存储在某个字节中的值之前是否需要屏蔽数字。
以这段代码为例:
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!!
我想知道,是否需要屏蔽b0
与 255 << 8
在移位之前获取 b1
的值?
注意:
我能想到在检索值之前进行屏蔽的唯一需要是是否有其他内容存储在较高字节中,例如尝试取回 b2
的值,其中将使用此代码:
Console.WriteLine(b0 & 255); //gets the value of b2
最佳答案
I want to find out, is there any need to mask b0 with 255 << 8 before shifting to get the value of b1?
不,没有必要。所以编译器会忽略屏蔽。有些人认为这使代码更容易理解或保护他们免受某些想象的故障情况的影响。它完全无害。
关于c# - 在检索存储在特定字节中的值之前是否需要屏蔽数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856348/