Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with the bits in a byte

Tags:

c#

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.

like image 623
Anonymous Avatar asked Jul 08 '13 09:07

Anonymous


People also ask

How do bits and bytes work?

Bits are usually assembled into a group of eight to form a byte. A byte contains enough information to store a single ASCII character, like "h". A kilobyte (KB) is 1,024 bytes, not one thousand bytes as might be expected, because computers use binary (base two) math, instead of a decimal (base ten) system.

What are the bits in a byte?

Bits and bytes Single bits are too small to be much use, so they are grouped together into units of 8 bits. Each 8-bit unit is called a byte. A byte is the basic unit which is passed around the computer, often in groups. Because of this the number 8 and its multiples have become important in computing.

Is a byte 8 or 10 bits?

The byte is a unit of digital information that most commonly consists of eight bits. Historically, the byte was the number of bits used to encode a single character of text in a computer and for this reason it is the smallest addressable unit of memory in many computer architectures.


1 Answers

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);
like image 60
dtb Avatar answered Oct 12 '22 05:10

dtb