如何使用字节中的位 [英] How to work with the bits in a byte

查看:79
本文介绍了如何使用字节中的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个值的字节。这里是文档:

I have a single byte which contains two values. Here's the documentation:


权限字节分为两个字段。最低的三个有效位承载用户的权限级别(0-5)。
的五个最高有效位带有一个覆盖拒绝阈值。如果将
的这些位设置为零,则系统拒绝阈值用于确定该用户的分数
是否被视为接受或拒绝。如果它们的
不为零,则这些位的值乘以10将是该用户的
阈值得分。

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.

授权字节:

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


我没有在C#中使用位的经验。

I don't have any experience of working with bits in C#.

有人可以帮我转换一个字节并获取如上所述的值吗?

Can someone please help me convert a Byte and get the values as mentioned above?

我尝试了以下代码:

BitArray BA = new BitArray(mybyte); 

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

But the length comes back as 29 and I would have expected 8, being each bit in the byte.

-感谢大家的快速帮助。现在就可以工作了!很棒的互联网。

-- Thanks for everyone's quick help. Got it working now! Awesome internet.

推荐答案

而不是 BitArray ,则可以更轻松地使用内置的按位与右-shift 运算符如下:

Instead of BitArray, you can more easily use the built-in bitwise AND and right-shift operator as follows:

byte authorityByte = ...

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

要取回单个字节,可以使用按位OR 左移运算符:

To get the single byte back, you can use the bitwise OR and left-shift operator:

int authorityLevel = ...
int rejectThreshold = ...

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

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

这篇关于如何使用字节中的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆