checking status of individual bits in C#

  • Thread starter Thread starter Daniel Passwater via DotNetMonster.com
  • Start date Start date
D

Daniel Passwater via DotNetMonster.com

I'm receiving a byte that contains the pass/fail test results of multiple tests. The first six bits are set. I need to read each of them separately. Is there an elegant way to do this?

Thanks in advance for any and all help.
 
Daniel,

I would create a BitArray instance, and then access the bits you want
with the indexer, like so:

// Create the BitArray instance.
BitArray bitArray = new BitArray(new byte[1]{ byteValue });

// Access the values.
// First bit, will be boolean.
Console.WriteLine(bitArray[0]);

Hope this helps.
 
Daniel Passwater via DotNetMonster.com said:
I'm receiving a byte that contains the pass/fail test results of
multiple tests. The first six bits are set. I need to read each of
them separately. Is there an elegant way to do this?

Use a bitwise and:

if ((x & 1) != 0)
....

if ((x & 2) != 0)
....

if ((x & 4) != 0)
....

etc
 
Back
Top