如何处理字节中的位

6

我有一个单字节包含两个值。以下是文档:

The authority byte is split into two fields. The three least significant bits carry the user’s authority level (0-5). The five most significant bits carry an override reject threshold. If these bits are set to zero, the system reject threshold is used to determine whether a score for this user is considered an accept or reject. If they are not zero, then the value of these bits multiplied by ten will be the threshold score for this user.

Authority Byte:

7 6 5 4 3 ......... 2 1 0
Reject Threshold .. Authority

我没有在C#中处理二进制数的经验。

有人可以帮我转换Byte并获取如上述的值吗?

我尝试了以下代码:

BitArray BA = new BitArray(mybyte); 

但是长度返回为29,而我期望的是8,即每个字节中的每一位。

-- 感谢大家的快速帮助。现在已经解决了!互联网太棒了。


1
你可能也会对这篇帖子感兴趣。 - Laurent S.
4个回答

7

您对 BitArray 的使用是不正确的。这样做:

BitArray BA = new BitArray(mybyte);

..将被隐式转换为 int。发生这种情况时,您将触发此构造函数:

BitArray(int length);

因此,它会创建具有特定长度的内容。
查看MSDN(http://msdn.microsoft.com/en-us/library/x1xda43a.aspx),您需要这样做:
BitArray BA = new BitArray(new byte[] { myByte });

长度将为8(如预期)。


7

不需要使用 BitArray,你可以更简单地使用内置的 按位与右移 运算符,如下所示:

byte authorityByte = ...

int authorityLevel = authorityByte & 7;
int rejectThreshold = authorityByte >> 3;

为了得到单字节,您可以使用位或和左移运算符:按位或左移运算符。
int authorityLevel = ...
int rejectThreshold = ...

Debug.Assert(authorityLevel >= 0 && authorityLevel <= 7);
Debug.Assert(rejectThreshold >= 0 && rejectThreshold <= 31);

byte authorityByte = (byte)((rejectThreshold << 3) | authorityLevel);

你能告诉我如何将这两个值转换回一个字节吗? - Anonymous

4

要将字节中前五位作为整数获取,将字节向右移动3(即8-5),并使用按位AND运算将三个高位设置为零,如下所示:

byte orig = ...
int rejThreshold = (orig >> 3) & 0x1F;
  • >>是“右移”运算符。它将位7到3移动到位置4到0,舍弃三个较低的位。
  • 0x1F是二进制数00011111,其中上三位设置为零,下五位设置为一。AND操作可以用于将此数字清零三个上位位。

这种技术可以推广到其他位模式和其他整数数据类型。您将想要的位移至最低有效位置,并应用一个“剪切”您想要的位数的掩码。在某些情况下,不需要移位(例如当您获取最低有效位组时)。在其他情况下,例如上面的示例中,不需要掩码,因为您可以在无符号类型中获取最高有效位组(如果类型为有符号,则需要进行AND操作)。


3

您正在使用错误的构造函数(可能是这样)。

您正在使用的可能是此构造函数,而您需要使用此构造函数

var bitArray = new BitArray(new [] { myByte } );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接