【问题标题】:Do you need to mask a number before retrieving the value stored at a certain byte?在检索存储在某个字节的值之前,是否需要屏蔽一个数字?
【发布时间】: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 &lt;&lt; 8 屏蔽b0

注意:
在检索值之前,我唯一能想到的屏蔽是是否在更高字节处存储了其他内容,例如尝试取回 b2 的值,其中将使用此代码:

Console.WriteLine(b0 & 255);  //gets the value of b2

【问题讨论】:

  • 如果您将b1b2 bytes 和b0 设置为ushort,这将非常明显。右移ushort 不会传播符号位。

标签: c# bit-manipulation bit-shift


【解决方案1】:

我想知道,在转移得到b1的值之前,是否需要用255

不,没有必要。所以编译器会省略屏蔽。有些人认为它使代码更容易理解或保护他们免受一些想象中的失败场景。它完全无害。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多