Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

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?

I've tried the following code:

BitArray BA = new BitArray(mybyte); 

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
261 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...