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

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c# - How to work with the bits in a byte

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...