Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte-array as bitfield in C#?

Is there a built-in class or something in .NET that would allow me to treat a byte-array as a large bitfield?

like image 830
Anon Avatar asked Jan 21 '11 16:01

Anon


1 Answers

Take a look at the BitArray class.

Here is an example explaining what is going on when using a byte array:

byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray myBA3 = new BitArray( myBytes );

Console.WriteLine( "myBA3" );
Console.WriteLine( "   Count:    {0}", myBA3.Count );
Console.WriteLine( "   Length:   {0}", myBA3.Length );
Console.WriteLine( "   Values:" );
PrintValues( myBA3, 8 );

public static void PrintValues( IEnumerable myList, int myWidth )
{
   int i = myWidth;
   foreach ( Object obj in myList )
   {
      if ( i <= 0 )
      {
         i = myWidth;
         Console.WriteLine();
      }
      i--;
      Console.Write( "{0,8}", obj );
   }
   Console.WriteLine();
}

This code produces the following output.

 myBA3
    Count:    40
    Length:   40
    Values:
     Bit0   Bit1    Bit2    Bit3    Bit4    Bit5    Bit6    Bit7
     True   False   False   False   False   False   False   False
     Bit8   Bit9    Bit10   Bit11   Bit12   Bit13   Bit14   Bit15 ... and so on
    False    True   False   False   False   False   False   False
     True    True   False   False   False   False   False   False
    False   False    True   False   False   False   False   False
     True   False    True   False   False   False   False   False
like image 151
SwDevMan81 Avatar answered Sep 30 '22 01:09

SwDevMan81