c# - 在检索存储在特定字节中的值之前是否需要屏蔽数字?

标签 c# bit-manipulation bit-shift

我想知道在进行位移位时,在检索存储在某个字节中的值之前是否需要屏蔽数字。

以这段代码为例:

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!!

我想知道,是否需要屏蔽b0255 << 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/

相关文章:

c - 为什么在一个表达式中同时使用左移和右移会有所不同?

c++ - 我的掩蔽是否正确

c# - 如何在Mono/MonoDevelop中使用System.Windows?

vbscript - VBScript中的 boolean 非运算符

c++ - 设置和取消设置 64 位整数中的特定位

algorithm - 二进制数字游戏之美

c++ - 从 Integer C++ 获取 n LSB

c# - 字符串替换不起作用

C#:区分 CurrentCulture 和 InvariantCulture 的单元测试

c# - 带有两个项目源的组合框